through2 4.0.2 → 5.0.1

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.
@@ -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,15 @@
1
+ ## [5.0.1](https://github.com/rvagg/through2/compare/v5.0.0...v5.0.1) (2026-05-15)
2
+
3
+ ### Bug Fixes
4
+
5
+ * add CJS support for Node.js 22.12+ ([#120](https://github.com/rvagg/through2/issues/120)) ([eef0aa0](https://github.com/rvagg/through2/commit/eef0aa044844c09b69ede525873c72579ea0c86a))
6
+
7
+ ## [5.0.0](https://github.com/rvagg/through2/compare/v4.0.2...v5.0.0) (2026-05-07)
8
+
9
+ ### ⚠ BREAKING CHANGES
10
+
11
+ * ESM rewrite, named exports, async + async-generator transforms, /web subpath (#118)
12
+
13
+ ### Features
14
+
15
+ * 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
- ![Build & Test](https://github.com/rvagg/through2/workflows/Build%20&%20Test/badge.svg)
3
+ [![NPM](https://nodei.co/npm/through2.svg?style=flat&data=n,v&color=blue)](https://nodei.co/npm/through2/)
4
4
 
5
- [![NPM](https://nodei.co/npm/through2.png?downloads&downloadRank)](https://nodei.co/npm/through2/)
5
+ **Tiny utilities for inserting transformation logic into Node.js streams and Web Streams pipelines.**
6
6
 
7
- **A tiny wrapper around Node.js streams.Transform (Streams2/3) to avoid explicit subclassing noise**
7
+ ```bash
8
+ npm install through2
9
+ ```
10
+
11
+ ```js
12
+ import { transform } from 'through2'
8
13
 
9
- Inspired by [Dominic Tarr](https://github.com/dominictarr)'s [through](https://github.com/dominictarr/through) in that it's so much easier to make a stream out of a function than it is to set up the prototype chain properly: `through(function (chunk) { ... })`.
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
- fs.createReadStream('ex.txt')
13
- .pipe(through2(function (chunk, enc, callback) {
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
- this.push(chunk)
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
- callback()
21
- }))
22
- .pipe(fs.createWriteStream('out.txt'))
23
- .on('finish', () => doSomethingSpecial())
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
- Or object streams:
66
+ Same idea for the modern, cross-runtime Web Streams API:
27
67
 
28
68
  ```js
29
- const all = []
69
+ import { transform } from 'through2/web'
30
70
 
31
- fs.createReadStream('data.csv')
32
- .pipe(csv2())
33
- .pipe(through2.obj(function (chunk, enc, callback) {
34
- const data = {
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
- callback()
42
- }))
43
- .on('data', (data) => {
44
- all.push(data)
45
- })
46
- .on('end', () => {
47
- doSomethingSpecial(all)
48
- })
76
+ ## Migrating from v4
77
+
78
+ v5 is a major version bump. Headline changes:
79
+
80
+ - **ESM source.** The package ships as ESM; new code should `import` it. CommonJS callers can still `require('through2')` on Node.js 22.12+ via `require(esm)`. On older Node, convert 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
- Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`.
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
- ## Do you need this?
139
+ ```js
140
+ import { objectTransform } from 'through2'
141
+ ```
54
142
 
55
- Since Node.js introduced [Simplified Stream Construction](https://nodejs.org/api/stream.html#stream_simplified_construction), many uses of **through2** have become redundant. Consider whether you really need to use **through2** or just want to use the `'readable-stream'` package, or the core `'stream'` package (which is derived from `'readable-stream'`):
143
+ ### Map
144
+
145
+ One in, one out. Async function form; the resolved value is pushed.
56
146
 
57
147
  ```js
58
- const { Transform } = require('readable-stream')
148
+ objectTransform(async (item) => doSomething(item))
149
+ ```
59
150
 
60
- const transformer = new Transform({
61
- transform(chunk, enc, callback) {
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
- ## API
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
- <b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b>
188
+ Side effect, pass through unchanged.
70
189
 
71
- Consult the **[stream.Transform](https://nodejs.org/docs/latest/api/stream.html#stream_class_stream_transform)** documentation for the exact rules of the `transformFunction` (i.e. `this._transform`) and the optional `flushFunction` (i.e. `this._flush`).
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
- ### options
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
- The options argument is optional and is passed straight through to `stream.Transform`. So you can use `objectMode:true` if you are processing non-binary streams (or just use `through2.obj()`).
213
+ ```bash
214
+ cat app.log | node example-ndjson.js warn
215
+ ```
76
216
 
77
- The `options` argument is first, unlike standard convention, because if I'm passing in an anonymous function then I'd prefer for the options argument to not get lost at the end of the call:
217
+ ## Node-style streams (`from 'through2'`)
78
218
 
79
219
  ```js
80
- fs.createReadStream('/tmp/important.dat')
81
- .pipe(through2({ objectMode: true, allowHalfOpen: false },
82
- (chunk, enc, cb) => {
83
- cb(null, 'wut?') // note we can use the second argument on the callback
84
- // to provide data as an alternative to this.push('wut?')
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
- .pipe(fs.createWriteStream('/tmp/wut.txt'))
237
+ this.push(chunk)
238
+ cb()
239
+ }))
240
+ .pipe(fs.createWriteStream('out.txt'))
88
241
  ```
89
242
 
90
- ### transformFunction
243
+ ### `objectTransform()`
91
244
 
92
- The `transformFunction` must have the following signature: `function (chunk, encoding, callback) {}`. A minimal implementation should call the `callback` function to indicate that the transformation is done, even if that transformation means discarding the chunk.
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
- To queue a new chunk, call `this.push(chunk)`&mdash;this can be called as many times as required before the `callback()` if you have multiple pieces to send on.
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
- Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error.
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
- If you **do not provide a `transformFunction`** then you will get a simple pass-through stream.
266
+ const a = Counter()
267
+ const b = new Counter({ highWaterMark: 32 }) // override per-call
268
+ ```
99
269
 
100
- ### flushFunction
270
+ ### Composing pipelines
101
271
 
102
- The optional `flushFunction` is provided as the last argument (2nd or 3rd, depending on whether you've supplied options) is called just prior to the stream ending. Can be used to finish up any processing that may be in progress.
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
- fs.createReadStream('/tmp/important.dat')
106
- .pipe(through2(
107
- (chunk, enc, cb) => cb(null, chunk), // transform is a noop
108
- function (cb) { // flush function
109
- this.push('tacking on an extra buffer to the end');
110
- cb();
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
- .pipe(fs.createWriteStream('/tmp/wut.txt'));
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
- <b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b>
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
- Instead of returning a `stream.Transform` instance, `through2.ctor()` returns a **constructor** for a custom Transform. This is useful when you want to use the same transform logic in multiple instances.
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
- const FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) {
122
- if (record.temp != null && record.unit == "F") {
123
- record.temp = ( ( record.temp - 32 ) * 5 ) / 9
124
- record.unit = "C"
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
- this.push(record)
127
- callback()
344
+ if (buf) yield buf
128
345
  })
129
346
 
130
- // Create instances of FToC like so:
131
- const converter = new FToC()
132
- // Or:
133
- const converter = FToC()
134
- // Or specify/override options when you instantiate, if you prefer:
135
- const converter = FToC({objectMode: true})
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 &copy; Rod Vagg and additional contributors and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
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
+ }