through2 4.0.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/dependabot.yml +20 -0
- package/.github/workflows/test-and-release.yml +72 -0
- package/CHANGELOG.md +9 -0
- package/README.md +314 -83
- package/example-ndjson.js +94 -0
- package/package.json +122 -21
- package/test/test.js +404 -0
- package/test/web.js +191 -0
- package/through2.js +267 -57
- package/tsconfig.json +25 -0
- package/types/through2.d.ts +91 -0
- package/types/through2.d.ts.map +1 -0
- package/types/web.d.ts +42 -0
- package/types/web.d.ts.map +1 -0
- package/web.js +241 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
version: 2
|
|
2
|
+
updates:
|
|
3
|
+
- package-ecosystem: 'github-actions'
|
|
4
|
+
directory: '/'
|
|
5
|
+
schedule:
|
|
6
|
+
interval: 'daily'
|
|
7
|
+
commit-message:
|
|
8
|
+
prefix: 'chore'
|
|
9
|
+
include: 'scope'
|
|
10
|
+
cooldown:
|
|
11
|
+
default-days: 5
|
|
12
|
+
- package-ecosystem: 'npm'
|
|
13
|
+
directory: '/'
|
|
14
|
+
schedule:
|
|
15
|
+
interval: 'daily'
|
|
16
|
+
commit-message:
|
|
17
|
+
prefix: 'chore'
|
|
18
|
+
include: 'scope'
|
|
19
|
+
cooldown:
|
|
20
|
+
default-days: 5
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
name: Test & Maybe Release
|
|
2
|
+
on: [push, pull_request]
|
|
3
|
+
|
|
4
|
+
jobs:
|
|
5
|
+
test:
|
|
6
|
+
strategy:
|
|
7
|
+
fail-fast: false
|
|
8
|
+
matrix:
|
|
9
|
+
node: [lts/*, current]
|
|
10
|
+
os: [macos-latest, ubuntu-latest, windows-latest]
|
|
11
|
+
runs-on: ${{ matrix.os }}
|
|
12
|
+
steps:
|
|
13
|
+
- name: Checkout Repository
|
|
14
|
+
uses: actions/checkout@v6.0.2
|
|
15
|
+
- name: Use Node.js ${{ matrix.node }}
|
|
16
|
+
uses: actions/setup-node@v6.4.0
|
|
17
|
+
with:
|
|
18
|
+
node-version: ${{ matrix.node }}
|
|
19
|
+
- name: Install Dependencies
|
|
20
|
+
run: npm install --no-progress
|
|
21
|
+
- name: Check build is up to date
|
|
22
|
+
run: |
|
|
23
|
+
npm run build
|
|
24
|
+
git diff --exit-code || (echo "::error::Build artifacts not committed. Run 'npm run build' and commit the changes." && exit 1)
|
|
25
|
+
- name: Lint
|
|
26
|
+
run: npm run lint
|
|
27
|
+
- name: Run node tests
|
|
28
|
+
run: npm run test:node
|
|
29
|
+
|
|
30
|
+
browser-test:
|
|
31
|
+
runs-on: ubuntu-latest
|
|
32
|
+
steps:
|
|
33
|
+
- name: Checkout Repository
|
|
34
|
+
uses: actions/checkout@v6.0.2
|
|
35
|
+
- name: Use Node.js lts/*
|
|
36
|
+
uses: actions/setup-node@v6.4.0
|
|
37
|
+
with:
|
|
38
|
+
node-version: lts/*
|
|
39
|
+
- name: Install Dependencies
|
|
40
|
+
run: npm install --no-progress
|
|
41
|
+
- name: Run browser tests
|
|
42
|
+
run: npm run test:browser
|
|
43
|
+
|
|
44
|
+
release:
|
|
45
|
+
name: Release
|
|
46
|
+
needs: [test, browser-test]
|
|
47
|
+
runs-on: ubuntu-latest
|
|
48
|
+
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
|
49
|
+
permissions:
|
|
50
|
+
contents: write
|
|
51
|
+
issues: write
|
|
52
|
+
pull-requests: write
|
|
53
|
+
id-token: write
|
|
54
|
+
steps:
|
|
55
|
+
- name: Checkout
|
|
56
|
+
uses: actions/checkout@v6.0.2
|
|
57
|
+
with:
|
|
58
|
+
fetch-depth: 0
|
|
59
|
+
- name: Setup Node.js
|
|
60
|
+
uses: actions/setup-node@v6.4.0
|
|
61
|
+
with:
|
|
62
|
+
node-version: lts/*
|
|
63
|
+
registry-url: 'https://registry.npmjs.org'
|
|
64
|
+
- name: Install dependencies
|
|
65
|
+
run: npm install --no-progress --no-package-lock --no-save
|
|
66
|
+
- name: Build
|
|
67
|
+
run: npm run build
|
|
68
|
+
- name: Release
|
|
69
|
+
env:
|
|
70
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
71
|
+
NPM_CONFIG_PROVENANCE: true
|
|
72
|
+
run: npx semantic-release
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
## [5.0.0](https://github.com/rvagg/through2/compare/v4.0.2...v5.0.0) (2026-05-07)
|
|
2
|
+
|
|
3
|
+
### ⚠ BREAKING CHANGES
|
|
4
|
+
|
|
5
|
+
* ESM rewrite, named exports, async + async-generator transforms, /web subpath (#118)
|
|
6
|
+
|
|
7
|
+
### Features
|
|
8
|
+
|
|
9
|
+
* ESM rewrite, named exports, async + async-generator transforms, /web subpath ([#118](https://github.com/rvagg/through2/issues/118)) ([dd40259](https://github.com/rvagg/through2/commit/dd40259b702c01243bb2d47a5fc855eb37534e06))
|
package/README.md
CHANGED
|
@@ -1,140 +1,371 @@
|
|
|
1
1
|
# through2
|
|
2
2
|
|
|
3
|
-
](https://nodei.co/npm/through2/)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
**Tiny utilities for inserting transformation logic into Node.js streams and Web Streams pipelines.**
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```bash
|
|
8
|
+
npm install through2
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { transform } from 'through2'
|
|
8
13
|
|
|
9
|
-
|
|
14
|
+
readableStream
|
|
15
|
+
.pipe(transform(async (chunk) => chunk.toString().toUpperCase()))
|
|
16
|
+
.pipe(writableStream)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Contents
|
|
20
|
+
|
|
21
|
+
* [Contents](#contents)
|
|
22
|
+
* [Why](#why)
|
|
23
|
+
* [Migrating from v4](#migrating-from-v4)
|
|
24
|
+
* [API](#api)
|
|
25
|
+
* [Transform function styles](#transform-function-styles)
|
|
26
|
+
* [Recipes](#recipes)
|
|
27
|
+
* [Map](#map)
|
|
28
|
+
* [Filter](#filter)
|
|
29
|
+
* [FlatMap](#flatmap)
|
|
30
|
+
* [Batch](#batch)
|
|
31
|
+
* [Tap](#tap)
|
|
32
|
+
* [Parse newline-delimited input](#parse-newline-delimited-input)
|
|
33
|
+
* [Node-style streams (`from 'through2'`)](#node-style-streams-from-through2)
|
|
34
|
+
* [`transform()`](#transform)
|
|
35
|
+
* [`objectTransform()`](#objecttransform)
|
|
36
|
+
* [`transformer()`](#transformer)
|
|
37
|
+
* [Composing pipelines](#composing-pipelines)
|
|
38
|
+
* [Default export (legacy)](#default-export-legacy)
|
|
39
|
+
* [Web Streams (`from 'through2/web'`)](#web-streams-from-through2web)
|
|
40
|
+
* [`transform()` (web)](#transform-web)
|
|
41
|
+
* [Implementation notes](#implementation-notes)
|
|
42
|
+
* [License](#license)
|
|
43
|
+
|
|
44
|
+
## Why
|
|
45
|
+
|
|
46
|
+
Writing a `Transform` stream usually means subclassing, wiring up `_transform`, choosing `objectMode`, and minding backpressure. **through2** wraps a function instead:
|
|
10
47
|
|
|
11
48
|
```js
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
for (let i = 0; i < chunk.length; i++)
|
|
15
|
-
if (chunk[i] == 97)
|
|
16
|
-
chunk[i] = 122 // swap 'a' for 'z'
|
|
49
|
+
// Without through2
|
|
50
|
+
import { Transform } from 'node:stream'
|
|
17
51
|
|
|
18
|
-
|
|
52
|
+
class Upper extends Transform {
|
|
53
|
+
_transform (chunk, _enc, cb) {
|
|
54
|
+
this.push(chunk.toString().toUpperCase())
|
|
55
|
+
cb()
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
input.pipe(new Upper()).pipe(output)
|
|
19
59
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
60
|
+
// With through2
|
|
61
|
+
import { transform } from 'through2'
|
|
62
|
+
|
|
63
|
+
input.pipe(transform(async (chunk) => chunk.toString().toUpperCase())).pipe(output)
|
|
24
64
|
```
|
|
25
65
|
|
|
26
|
-
|
|
66
|
+
Same idea for the modern, cross-runtime Web Streams API:
|
|
27
67
|
|
|
28
68
|
```js
|
|
29
|
-
|
|
69
|
+
import { transform } from 'through2/web'
|
|
30
70
|
|
|
31
|
-
|
|
32
|
-
.
|
|
33
|
-
.
|
|
34
|
-
|
|
35
|
-
name : chunk[0]
|
|
36
|
-
, address : chunk[3]
|
|
37
|
-
, phone : chunk[10]
|
|
38
|
-
}
|
|
39
|
-
this.push(data)
|
|
71
|
+
await response.body
|
|
72
|
+
.pipeThrough(transform(async (chunk) => /* ... */))
|
|
73
|
+
.pipeTo(destination)
|
|
74
|
+
```
|
|
40
75
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
76
|
+
## Migrating from v4
|
|
77
|
+
|
|
78
|
+
v5 is a major version bump. Headline changes:
|
|
79
|
+
|
|
80
|
+
- **ESM only.** `require('through2')` no longer works. Convert callers to `import` or pin to `through2@4`.
|
|
81
|
+
- **Named exports added.** `transform`, `objectTransform`, `transformer` are the preferred surface in new code.
|
|
82
|
+
- **Default export still works.** `through2(fn)`, `through2.obj(fn)`, and `through2.ctor(fn)` produce equivalent stream instances. Once your callers are converted to ESM imports, the call-site syntax and runtime behaviour are unchanged (modulo the `instanceof` caveat below).
|
|
83
|
+
- **Async functions and async generators are now accepted** as transform functions, in addition to the classic `(chunk, enc, cb)` callback form. See [Transform function styles](#transform-function-styles).
|
|
84
|
+
- **`through2/web` subpath added** for Web Streams (`TransformStream`) pipelines.
|
|
85
|
+
- **`readable-stream@4`** (was `@3`) is the underlying dependency.
|
|
86
|
+
- **`transformer` / `.ctor` returns a factory function**, not a true constructor. The returned instance is still a `Transform`, but `instanceof YourFactory` no longer holds. Use `instanceof Transform` instead.
|
|
87
|
+
|
|
88
|
+
Mapping for legacy code:
|
|
89
|
+
|
|
90
|
+
| v4 / legacy | v5 named export |
|
|
91
|
+
| --------------------- | ------------------------------ |
|
|
92
|
+
| `through2(fn)` | `transform(fn)` |
|
|
93
|
+
| `through2.obj(fn)` | `objectTransform(fn)` |
|
|
94
|
+
| `through2.ctor(fn)` | `transformer(fn)` |
|
|
95
|
+
|
|
96
|
+
## API
|
|
97
|
+
|
|
98
|
+
Two import paths, mirroring the two stream worlds:
|
|
99
|
+
|
|
100
|
+
| Import | Stream API | Returns | Use when |
|
|
101
|
+
| ---------------------------- | ---------------------------- | ---------------------- | ------------------------------------------------ |
|
|
102
|
+
| `from 'through2'` | Node-style streams | `stream.Transform` | You're working with `Readable`/`Writable`/`Transform`-shaped streams (`.pipe(...)`) |
|
|
103
|
+
| `from 'through2/web'` | Web Streams (WHATWG) | `TransformStream` | You're working with `ReadableStream`/`WritableStream`-shaped streams (`.pipeThrough(...)`) |
|
|
104
|
+
|
|
105
|
+
The two entries differ in the *stream API* they target, not the runtime they run on. Either entry can run in Node.js, browsers, Deno, Bun, or Cloudflare Workers. Pick the one that matches the streams you're piping with.
|
|
106
|
+
|
|
107
|
+
- **`from 'through2'`** uses the Node-style streams API (`Readable`/`Writable`/`Transform`, `.pipe()`, callback-driven `_transform`). It depends on [`readable-stream`](https://github.com/nodejs/readable-stream); browser bundlers pick up that package's `browser` field automatically and ship its self-contained shim, so no Node-builtin polyfill is needed.
|
|
108
|
+
- **`from 'through2/web'`** uses the WHATWG Web Streams API (`TransformStream`, `.pipeThrough()`). Zero runtime dependencies; relies only on `TransformStream` being a global (it is in modern browsers, Node.js >= 18, Deno, Bun, Workers).
|
|
109
|
+
|
|
110
|
+
### Transform function styles
|
|
111
|
+
|
|
112
|
+
Every transform-creating export accepts the same three function styles, auto-dispatched by inspecting the function's kind:
|
|
113
|
+
|
|
114
|
+
```js
|
|
115
|
+
// 1. Classic Node-style callback (use `this.push()` and the callback)
|
|
116
|
+
transform(function (chunk, encoding, callback) {
|
|
117
|
+
this.push(chunk)
|
|
118
|
+
callback()
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
// 2. Async function (resolved value is pushed; `undefined` skips)
|
|
122
|
+
transform(async (chunk) => chunk.toString().toUpperCase())
|
|
123
|
+
|
|
124
|
+
// 3. Async generator (1-to-many; full pipeline coroutine)
|
|
125
|
+
transform(async function * (source) {
|
|
126
|
+
for await (const chunk of source) {
|
|
127
|
+
yield chunk
|
|
128
|
+
yield chunk
|
|
129
|
+
}
|
|
130
|
+
})
|
|
49
131
|
```
|
|
50
132
|
|
|
51
|
-
|
|
133
|
+
A flush function may be passed as the trailing argument; it follows the same dispatch rules.
|
|
134
|
+
|
|
135
|
+
> **Note on async**: the async function form does **not** use `this.push`. To emit zero or many chunks per input, use the async generator form. To emit one chunk per input (or skip), return the value (or `undefined`).
|
|
136
|
+
|
|
137
|
+
## Recipes
|
|
52
138
|
|
|
53
|
-
|
|
139
|
+
```js
|
|
140
|
+
import { objectTransform } from 'through2'
|
|
141
|
+
```
|
|
54
142
|
|
|
55
|
-
|
|
143
|
+
### Map
|
|
144
|
+
|
|
145
|
+
One in, one out. Async function form; the resolved value is pushed.
|
|
56
146
|
|
|
57
147
|
```js
|
|
58
|
-
|
|
148
|
+
objectTransform(async (item) => doSomething(item))
|
|
149
|
+
```
|
|
59
150
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
151
|
+
### Filter
|
|
152
|
+
|
|
153
|
+
Return `undefined` to drop a chunk.
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
objectTransform(async (item) => predicate(item) ? item : undefined)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### FlatMap
|
|
160
|
+
|
|
161
|
+
One in, many out. Async generator form.
|
|
162
|
+
|
|
163
|
+
```js
|
|
164
|
+
objectTransform(async function * (source) {
|
|
165
|
+
for await (const item of source) {
|
|
166
|
+
for (const x of expand(item)) yield x
|
|
63
167
|
}
|
|
64
168
|
})
|
|
65
169
|
```
|
|
66
170
|
|
|
67
|
-
|
|
171
|
+
### Batch
|
|
172
|
+
|
|
173
|
+
Collect a fixed-size batch, emit at size or at flush.
|
|
174
|
+
|
|
175
|
+
```js
|
|
176
|
+
objectTransform(async function * (source) {
|
|
177
|
+
let batch = []
|
|
178
|
+
for await (const item of source) {
|
|
179
|
+
batch.push(item)
|
|
180
|
+
if (batch.length >= 100) { yield batch; batch = [] }
|
|
181
|
+
}
|
|
182
|
+
if (batch.length) yield batch
|
|
183
|
+
})
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Tap
|
|
68
187
|
|
|
69
|
-
|
|
188
|
+
Side effect, pass through unchanged.
|
|
70
189
|
|
|
71
|
-
|
|
190
|
+
```js
|
|
191
|
+
objectTransform(async (item) => { observe(item); return item })
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Parse newline-delimited input
|
|
195
|
+
|
|
196
|
+
Byte chunks in, line strings out. The async generator buffers across chunk boundaries.
|
|
197
|
+
|
|
198
|
+
```js
|
|
199
|
+
objectTransform(async function * (source) {
|
|
200
|
+
let buf = ''
|
|
201
|
+
for await (const chunk of source) {
|
|
202
|
+
buf += chunk.toString()
|
|
203
|
+
const lines = buf.split('\n')
|
|
204
|
+
buf = lines.pop()
|
|
205
|
+
for (const line of lines) yield line
|
|
206
|
+
}
|
|
207
|
+
if (buf) yield buf
|
|
208
|
+
})
|
|
209
|
+
```
|
|
72
210
|
|
|
73
|
-
|
|
211
|
+
For a runnable end-to-end demo combining NDJSON parsing, level filtering, formatting, and a tally, see [`example-ndjson.js`](./example-ndjson.js):
|
|
74
212
|
|
|
75
|
-
|
|
213
|
+
```bash
|
|
214
|
+
cat app.log | node example-ndjson.js warn
|
|
215
|
+
```
|
|
76
216
|
|
|
77
|
-
|
|
217
|
+
## Node-style streams (`from 'through2'`)
|
|
78
218
|
|
|
79
219
|
```js
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
220
|
+
import { transform, objectTransform, transformer } from 'through2'
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### `transform()`
|
|
224
|
+
|
|
225
|
+
```
|
|
226
|
+
transform([options], transformFn[, flushFn]) -> stream.Transform
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Returns a `stream.Transform`. `options` is forwarded to the underlying `Transform` constructor. If `transformFn` is omitted, a passthrough is returned.
|
|
230
|
+
|
|
231
|
+
```js
|
|
232
|
+
fs.createReadStream('in.txt')
|
|
233
|
+
.pipe(transform(function (chunk, _enc, cb) {
|
|
234
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
235
|
+
if (chunk[i] === 97) chunk[i] = 122 // swap 'a' for 'z'
|
|
85
236
|
}
|
|
86
|
-
|
|
87
|
-
|
|
237
|
+
this.push(chunk)
|
|
238
|
+
cb()
|
|
239
|
+
}))
|
|
240
|
+
.pipe(fs.createWriteStream('out.txt'))
|
|
88
241
|
```
|
|
89
242
|
|
|
90
|
-
###
|
|
243
|
+
### `objectTransform()`
|
|
91
244
|
|
|
92
|
-
|
|
245
|
+
```
|
|
246
|
+
objectTransform([options], transformFn[, flushFn]) -> stream.Transform
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Like `transform`, with `objectMode: true` enabled by default. Most async/async-generator use cases want this.
|
|
250
|
+
|
|
251
|
+
### `transformer()`
|
|
252
|
+
|
|
253
|
+
```
|
|
254
|
+
transformer([options], transformFn[, flushFn]) -> (overrideOptions?) -> stream.Transform
|
|
255
|
+
```
|
|
93
256
|
|
|
94
|
-
|
|
257
|
+
Returns a factory function. Calling it (with or without `new`) produces a fresh `Transform` instance with the configured behaviour. Per-call options merge on top of the configured defaults; the merged options are exposed as `this.options` inside the transform function.
|
|
95
258
|
|
|
96
|
-
|
|
259
|
+
```js
|
|
260
|
+
const Counter = transformer({ objectMode: true }, function (chunk, _enc, cb) {
|
|
261
|
+
this.count = (this.count || 0) + 1
|
|
262
|
+
this.push(chunk)
|
|
263
|
+
cb()
|
|
264
|
+
})
|
|
97
265
|
|
|
98
|
-
|
|
266
|
+
const a = Counter()
|
|
267
|
+
const b = new Counter({ highWaterMark: 32 }) // override per-call
|
|
268
|
+
```
|
|
99
269
|
|
|
100
|
-
###
|
|
270
|
+
### Composing pipelines
|
|
101
271
|
|
|
102
|
-
|
|
272
|
+
For anything beyond a quick demo, prefer `node:stream/promises`'s `pipeline()` over chained `.pipe()`. It propagates errors, awaits completion, and destroys all streams on failure (chained `.pipe()` silently leaves streams hanging on error).
|
|
103
273
|
|
|
104
274
|
```js
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
275
|
+
import { pipeline } from 'node:stream/promises'
|
|
276
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
277
|
+
import { objectTransform } from 'through2'
|
|
278
|
+
|
|
279
|
+
await pipeline(
|
|
280
|
+
createReadStream('in.ndjson'),
|
|
281
|
+
objectTransform(async function * (source) {
|
|
282
|
+
let buf = ''
|
|
283
|
+
for await (const chunk of source) {
|
|
284
|
+
buf += chunk.toString()
|
|
285
|
+
const lines = buf.split('\n')
|
|
286
|
+
buf = lines.pop()
|
|
287
|
+
for (const line of lines) yield JSON.parse(line)
|
|
111
288
|
}
|
|
112
|
-
)
|
|
113
|
-
|
|
289
|
+
}),
|
|
290
|
+
objectTransform(async (record) => record.active ? record : undefined),
|
|
291
|
+
objectTransform(async (record) => JSON.stringify(record) + '\n'),
|
|
292
|
+
createWriteStream('out.ndjson')
|
|
293
|
+
)
|
|
114
294
|
```
|
|
115
295
|
|
|
116
|
-
|
|
296
|
+
`pipeline()` accepts any mix of through2-built transforms and other `Readable`/`Writable`/`Transform` instances. Use it whenever the pipeline can fail or you need to know when it's done.
|
|
297
|
+
|
|
298
|
+
A runnable, more elaborate version of this NDJSON pipeline lives in [`example-ndjson.js`](./example-ndjson.js) (parses arbitrary structured logs from stdin, filters by level, pretty-prints to stdout, summarises on stderr).
|
|
299
|
+
|
|
300
|
+
### Default export (legacy)
|
|
301
|
+
|
|
302
|
+
The default export is `transform` with `.obj` and `.ctor` attached for back-compatibility:
|
|
117
303
|
|
|
118
|
-
|
|
304
|
+
```js
|
|
305
|
+
import through2 from 'through2'
|
|
306
|
+
|
|
307
|
+
through2(fn) // === transform(fn)
|
|
308
|
+
through2.obj(fn) // === objectTransform(fn)
|
|
309
|
+
through2.ctor(fn) // === transformer(fn)
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
## Web Streams (`from 'through2/web'`)
|
|
119
313
|
|
|
120
314
|
```js
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
315
|
+
import { transform } from 'through2/web'
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
### `transform()` (web)
|
|
319
|
+
|
|
320
|
+
```
|
|
321
|
+
transform([transformFn][, flushFn]) -> TransformStream
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
Returns a `TransformStream`. The classic-style function takes `(chunk, controller)` and uses `controller.enqueue()`. Async and async-generator forms work the same as in the Node-style streams entry.
|
|
325
|
+
|
|
326
|
+
```js
|
|
327
|
+
// 1-to-many fan-out (controller form, stateless)
|
|
328
|
+
const tagged = transform((chunk, controller) => {
|
|
329
|
+
controller.enqueue({ kind: 'raw', value: chunk })
|
|
330
|
+
controller.enqueue({ kind: 'upper', value: chunk.toString().toUpperCase() })
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
// Splitter: cross-chunk state is needed (a line can span chunks). The async
|
|
334
|
+
// generator form lets the buffer be a local variable; the classic controller
|
|
335
|
+
// form would need closure state plus a flush handler.
|
|
336
|
+
const splitter = transform(async function * (source) {
|
|
337
|
+
let buf = ''
|
|
338
|
+
for await (const chunk of source) {
|
|
339
|
+
buf += chunk.toString()
|
|
340
|
+
const lines = buf.split('\n')
|
|
341
|
+
buf = lines.pop()
|
|
342
|
+
for (const line of lines) yield line
|
|
125
343
|
}
|
|
126
|
-
|
|
127
|
-
callback()
|
|
344
|
+
if (buf) yield buf
|
|
128
345
|
})
|
|
129
346
|
|
|
130
|
-
//
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
347
|
+
// Async (1-to-1) with flush
|
|
348
|
+
const withTrailer = transform(
|
|
349
|
+
async (chunk) => chunk.toString().toUpperCase(),
|
|
350
|
+
(controller) => controller.enqueue('END')
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
// Pipe a fetch response through a transform
|
|
354
|
+
await response.body
|
|
355
|
+
.pipeThrough(transform(async (chunk) => chunk))
|
|
356
|
+
.pipeTo(destinationWritableStream)
|
|
136
357
|
```
|
|
137
358
|
|
|
359
|
+
### Implementation notes
|
|
360
|
+
|
|
361
|
+
At the time of writing, Chromium hasn't shipped the cleanup hook that `TransformStream` would use to tear down an in-flight async generator on cancel. Without a workaround, calling `reader.cancel()` on a browser-side pipeline would leave your `async function *` suspended and its `finally` block would never run. The web entry handles this for you:
|
|
362
|
+
|
|
363
|
+
- Backpressure works in both directions through `pipeThrough`.
|
|
364
|
+
- Cancelling the consumer or aborting the producer cleans up your generator (its `finally` runs) and errors the other side.
|
|
365
|
+
- Same behaviour in browsers, Node.js, Deno, Bun, and Cloudflare Workers.
|
|
366
|
+
|
|
367
|
+
One thing to note: `transform(asyncGenFn)` returns a `{ readable, writable }` pair rather than a `TransformStream` instance. `pipeThrough` and `pipeTo` accept it identically.
|
|
368
|
+
|
|
138
369
|
## License
|
|
139
370
|
|
|
140
|
-
**through2** is Copyright
|
|
371
|
+
**through2** is Copyright (c) Rod Vagg and additional contributors and licensed under the MIT license. See the included LICENSE file for more details.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// example-ndjson.js
|
|
2
|
+
//
|
|
3
|
+
// Reads NDJSON log entries from stdin, filters by minimum level, pretty-prints
|
|
4
|
+
// matches to stdout, writes a summary to stderr. A small demonstration of
|
|
5
|
+
// composing through2 transforms with `node:stream/promises` `pipeline()`.
|
|
6
|
+
//
|
|
7
|
+
// Usage:
|
|
8
|
+
// cat app.log | node example-ndjson.js [minLevel]
|
|
9
|
+
//
|
|
10
|
+
// Recognises common shapes for level / timestamp / logger / message fields,
|
|
11
|
+
// so it works with structured logs from zap (Go), pino (Node.js), bunyan,
|
|
12
|
+
// winston, and similar.
|
|
13
|
+
|
|
14
|
+
import { pipeline } from 'node:stream/promises'
|
|
15
|
+
import { objectTransform } from './through2.js'
|
|
16
|
+
|
|
17
|
+
const minLevel = (process.argv[2] || 'warn').toLowerCase()
|
|
18
|
+
|
|
19
|
+
// Map common level names + pino numeric levels to a single ordinal scale.
|
|
20
|
+
const levelNames = {
|
|
21
|
+
trace: 0,
|
|
22
|
+
debug: 1,
|
|
23
|
+
info: 2,
|
|
24
|
+
notice: 2,
|
|
25
|
+
warn: 3,
|
|
26
|
+
warning: 3,
|
|
27
|
+
error: 4,
|
|
28
|
+
err: 4,
|
|
29
|
+
fatal: 5,
|
|
30
|
+
crit: 5,
|
|
31
|
+
critical: 5,
|
|
32
|
+
panic: 5,
|
|
33
|
+
dpanic: 5
|
|
34
|
+
}
|
|
35
|
+
const pinoNumeric = (n) =>
|
|
36
|
+
n >= 60 ? 5 : n >= 50 ? 4 : n >= 40 ? 3 : n >= 30 ? 2 : n >= 20 ? 1 : 0
|
|
37
|
+
const lvlIdx = (l) =>
|
|
38
|
+
typeof l === 'number' ? pinoNumeric(l) : levelNames[String(l).toLowerCase()] ?? 0
|
|
39
|
+
|
|
40
|
+
const minIdx = lvlIdx(minLevel)
|
|
41
|
+
|
|
42
|
+
let scanned = 0
|
|
43
|
+
let matched = 0
|
|
44
|
+
const byLogger = new Map()
|
|
45
|
+
|
|
46
|
+
await pipeline(
|
|
47
|
+
process.stdin,
|
|
48
|
+
|
|
49
|
+
// 1. Parse NDJSON: byte chunks in, objects out. The async generator handles
|
|
50
|
+
// line splitting across chunk boundaries.
|
|
51
|
+
objectTransform(async function * (source) {
|
|
52
|
+
let buf = ''
|
|
53
|
+
for await (const chunk of source) {
|
|
54
|
+
buf += chunk.toString()
|
|
55
|
+
const lines = buf.split('\n')
|
|
56
|
+
buf = lines.pop()
|
|
57
|
+
for (const line of lines) {
|
|
58
|
+
scanned++
|
|
59
|
+
if (!line) continue
|
|
60
|
+
try { yield JSON.parse(line) } catch { /* skip non-JSON */ }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (buf.trim()) try { yield JSON.parse(buf) } catch { /* skip non-JSON */ }
|
|
64
|
+
}),
|
|
65
|
+
|
|
66
|
+
// 2. Filter by minimum level. Returning undefined from an async transform
|
|
67
|
+
// drops the chunk.
|
|
68
|
+
objectTransform(async (entry) =>
|
|
69
|
+
lvlIdx(entry.level) >= minIdx ? entry : undefined
|
|
70
|
+
),
|
|
71
|
+
|
|
72
|
+
// 3. Format each match as a one-line text record; tally as we go.
|
|
73
|
+
objectTransform(async (entry) => {
|
|
74
|
+
matched++
|
|
75
|
+
const logger = entry.logger || entry.name || entry.component || '-'
|
|
76
|
+
byLogger.set(logger, (byLogger.get(logger) || 0) + 1)
|
|
77
|
+
const ts = String(entry.ts || entry.time || '').slice(0, 19).padEnd(19)
|
|
78
|
+
const lvl = String(entry.level).padEnd(5).slice(0, 5)
|
|
79
|
+
const msg = entry.msg || entry.message || ''
|
|
80
|
+
return `${ts} ${lvl} ${logger.padEnd(20).slice(0, 20)} ${msg}\n`
|
|
81
|
+
}),
|
|
82
|
+
|
|
83
|
+
process.stdout
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
const fmt = (n) => n.toLocaleString()
|
|
87
|
+
process.stderr.write('\n--\n')
|
|
88
|
+
process.stderr.write(`${fmt(scanned)} lines scanned, ${fmt(matched)} matched (level >= ${minLevel})\n`)
|
|
89
|
+
if (byLogger.size > 0) {
|
|
90
|
+
process.stderr.write('top loggers:\n')
|
|
91
|
+
for (const [k, v] of [...byLogger.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)) {
|
|
92
|
+
process.stderr.write(` ${fmt(v).padStart(8)} ${k}\n`)
|
|
93
|
+
}
|
|
94
|
+
}
|