{"name":"through2","version":"5.0.3","keywords":["stream","transform","transformstream","web-streams","async-iterable","pipeline"],"author":{"url":"https://github.com/rvagg","name":"Rod Vagg","email":"r@va.gg"},"license":"MIT","_id":"through2@5.0.3","maintainers":[{"name":"bryce","email":"bryce@ravenwall.com"},{"name":"rvagg","email":"r@va.gg"}],"homepage":"https://github.com/rvagg/through2","bugs":{"url":"https://github.com/rvagg/through2/issues"},"dist":{"shasum":"e47fa5c454a44b0806806f96d4f3bbf5a17c6f3a","tarball":"http://registry-npm.ywwl.com/through2/download/through2-5.0.3.tgz","fileCount":16,"integrity":"sha512-nqwUEnCIHJraWAVq+VypWHsyRFxQLqilCdYIVfBqatuPnMehVz3+B6zGRNnUHqlUlEsx22JOY43FSWBHQlxVZA==","signatures":[{"sig":"MEQCIF7I+1s78+ovetd0Zh/SBMRTTJ889VNcgzScjEeVlEmBAiAs+qXUTW1v6d5bV1Vb7L+ndpZLkSS8u2XtP8qHw5/IIw==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/through2@5.0.3","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":68897,"size":17960,"noattachment":false,"key":"/through2/-/through2-5.0.3.tgz"},"main":"./through2.js","type":"module","types":"./types/through2.d.ts","exports":{".":{"types":"./types/through2.d.ts","import":"./through2.js","require":"./through2.js"},"./web":{"types":"./types/web.d.ts","import":"./web.js","require":"./web.js"}},"gitHead":"bacbffbde629d2f2ee302e6f1cb16efa28d8f69b","release":{"plugins":[["@semantic-release/commit-analyzer",{"preset":"conventionalcommits","releaseRules":[{"release":"major","breaking":true},{"revert":true,"release":"patch"},{"type":"feat","release":"minor"},{"type":"fix","release":"patch"},{"type":"chore","release":"patch"},{"type":"docs","release":"patch"},{"type":"test","release":"patch"},{"scope":"no-release","release":false}]}],["@semantic-release/release-notes-generator",{"preset":"conventionalcommits","presetConfig":{"types":[{"type":"feat","section":"Features"},{"type":"fix","section":"Bug Fixes"},{"type":"chore","section":"Trivial Changes"},{"type":"docs","section":"Trivial Changes"},{"type":"test","section":"Tests"}]}}],"@semantic-release/changelog","@semantic-release/npm","@semantic-release/github","@semantic-release/git"],"branches":["master"]},"scripts":{"lint":"standard","test":"npm run lint && npm run test:node","build":"npm run build:types","test:ci":"npm run lint && npm run test:node && npm run test:browser","test:node":"polendina-node bare-async test/test.js test/web.js","build:types":"tsc --build","test:browser":"polendina --cleanup --runner=bare-async test/test.js test/web.js"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:67030ff9-28b5-461f-922f-71d28d8c48ae"}},"repository":{"url":"git+https://github.com/rvagg/through2.git","type":"git"},"_npmVersion":"11.17.0","description":"Tiny utilities for inserting transformation logic into Node.js stream and Web Streams pipelines","directories":{},"_nodeVersion":"24.16.0","dependencies":{"readable-stream":"^4.7.0"},"_hasShrinkwrap":false,"devDependencies":{"standard":"^17.1.2","polendina":"^3.2.21","typescript":"^6.0.3","@types/node":"^25.6.0","semantic-release":"^25.0.3","@semantic-release/git":"^10.0.1","@semantic-release/npm":"^13.1.5","@semantic-release/github":"^12.0.6","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/release-notes-generator":"^14.1.0","conventional-changelog-conventionalcommits":"^9.3.1"},"_npmOperationalInternal":{"tmp":"tmp/through2_5.0.3_1782191082105_0.09473732312963246","host":"s3://npm-registry-packages-npm-production"},"readme":"# through2\n\n[![NPM](https://nodei.co/npm/through2.svg?style=flat&data=n,v&color=blue)](https://nodei.co/npm/through2/)\n\n**Tiny utilities for inserting transformation logic into Node.js streams and Web Streams pipelines.**\n\n```bash\nnpm install through2\n```\n\n```js\nimport { transform } from 'through2'\n\nreadableStream\n  .pipe(transform(async (chunk) => chunk.toString().toUpperCase()))\n  .pipe(writableStream)\n```\n\n## Contents\n\n* [Contents](#contents)\n* [Why](#why)\n* [Migrating from v4](#migrating-from-v4)\n* [API](#api)\n  * [Transform function styles](#transform-function-styles)\n* [Recipes](#recipes)\n  * [Map](#map)\n  * [Filter](#filter)\n  * [FlatMap](#flatmap)\n  * [Batch](#batch)\n  * [Tap](#tap)\n  * [Parse newline-delimited input](#parse-newline-delimited-input)\n* [Node-style streams (`from 'through2'`)](#node-style-streams-from-through2)\n  * [`transform()`](#transform)\n  * [`objectTransform()`](#objecttransform)\n  * [`transformer()`](#transformer)\n  * [Composing pipelines](#composing-pipelines)\n  * [Default export (legacy)](#default-export-legacy)\n* [Web Streams (`from 'through2/web'`)](#web-streams-from-through2web)\n  * [`transform()` (web)](#transform-web)\n  * [Implementation notes](#implementation-notes)\n* [License](#license)\n\n## Why\n\nWriting a `Transform` stream usually means subclassing, wiring up `_transform`, choosing `objectMode`, and minding backpressure. **through2** wraps a function instead:\n\n```js\n// Without through2\nimport { Transform } from 'node:stream'\n\nclass Upper extends Transform {\n  _transform (chunk, _enc, cb) {\n    this.push(chunk.toString().toUpperCase())\n    cb()\n  }\n}\ninput.pipe(new Upper()).pipe(output)\n\n// With through2\nimport { transform } from 'through2'\n\ninput.pipe(transform(async (chunk) => chunk.toString().toUpperCase())).pipe(output)\n```\n\nSame idea for the modern, cross-runtime Web Streams API:\n\n```js\nimport { transform } from 'through2/web'\n\nawait response.body\n  .pipeThrough(transform(async (chunk) => /* ... */))\n  .pipeTo(destination)\n```\n\n## Migrating from v4\n\nv5 is a major version bump. Headline changes:\n\n- **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`.\n- **Named exports added.** `transform`, `objectTransform`, `transformer` are the preferred surface in new code.\n- **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).\n- **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).\n- **`through2/web` subpath added** for Web Streams (`TransformStream`) pipelines.\n- **`readable-stream@4`** (was `@3`) is the underlying dependency.\n- **`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.\n\nMapping for legacy code:\n\n| v4 / legacy           | v5 named export                |\n| --------------------- | ------------------------------ |\n| `through2(fn)`        | `transform(fn)`                |\n| `through2.obj(fn)`    | `objectTransform(fn)`          |\n| `through2.ctor(fn)`   | `transformer(fn)`              |\n\n## API\n\nTwo import paths, mirroring the two stream worlds:\n\n| Import                       | Stream API                   | Returns                | Use when                                         |\n| ---------------------------- | ---------------------------- | ---------------------- | ------------------------------------------------ |\n| `from 'through2'`            | Node-style streams           | `stream.Transform`     | You're working with `Readable`/`Writable`/`Transform`-shaped streams (`.pipe(...)`) |\n| `from 'through2/web'`        | Web Streams (WHATWG)         | `TransformStream`      | You're working with `ReadableStream`/`WritableStream`-shaped streams (`.pipeThrough(...)`) |\n\nThe 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.\n\n- **`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.\n- **`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).\n\n### Transform function styles\n\nEvery transform-creating export accepts the same three function styles, auto-dispatched by inspecting the function's kind:\n\n```js\n// 1. Classic Node-style callback (use `this.push()` and the callback)\ntransform(function (chunk, encoding, callback) {\n  this.push(chunk)\n  callback()\n})\n\n// 2. Async function (resolved value is pushed; `undefined` skips)\ntransform(async (chunk) => chunk.toString().toUpperCase())\n\n// 3. Async generator (1-to-many; full pipeline coroutine)\ntransform(async function * (source) {\n  for await (const chunk of source) {\n    yield chunk\n    yield chunk\n  }\n})\n```\n\nA flush function may be passed as the trailing argument; it follows the same dispatch rules.\n\n> **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`).\n\n## Recipes\n\n```js\nimport { objectTransform } from 'through2'\n```\n\n### Map\n\nOne in, one out. Async function form; the resolved value is pushed.\n\n```js\nobjectTransform(async (item) => doSomething(item))\n```\n\n### Filter\n\nReturn `undefined` to drop a chunk.\n\n```js\nobjectTransform(async (item) => predicate(item) ? item : undefined)\n```\n\n### FlatMap\n\nOne in, many out. Async generator form.\n\n```js\nobjectTransform(async function * (source) {\n  for await (const item of source) {\n    for (const x of expand(item)) yield x\n  }\n})\n```\n\n### Batch\n\nCollect a fixed-size batch, emit at size or at flush.\n\n```js\nobjectTransform(async function * (source) {\n  let batch = []\n  for await (const item of source) {\n    batch.push(item)\n    if (batch.length >= 100) { yield batch; batch = [] }\n  }\n  if (batch.length) yield batch\n})\n```\n\n### Tap\n\nSide effect, pass through unchanged.\n\n```js\nobjectTransform(async (item) => { observe(item); return item })\n```\n\n### Parse newline-delimited input\n\nByte chunks in, line strings out. The async generator buffers across chunk boundaries.\n\n```js\nobjectTransform(async function * (source) {\n  let buf = ''\n  for await (const chunk of source) {\n    buf += chunk.toString()\n    const lines = buf.split('\\n')\n    buf = lines.pop()\n    for (const line of lines) yield line\n  }\n  if (buf) yield buf\n})\n```\n\nFor a runnable end-to-end demo combining NDJSON parsing, level filtering, formatting, and a tally, see [`example-ndjson.js`](./example-ndjson.js):\n\n```bash\ncat app.log | node example-ndjson.js warn\n```\n\n## Node-style streams (`from 'through2'`)\n\n```js\nimport { transform, objectTransform, transformer } from 'through2'\n```\n\n### `transform()`\n\n```\ntransform([options], transformFn[, flushFn]) -> stream.Transform\n```\n\nReturns a `stream.Transform`. `options` is forwarded to the underlying `Transform` constructor. If `transformFn` is omitted, a passthrough is returned.\n\n```js\nfs.createReadStream('in.txt')\n  .pipe(transform(function (chunk, _enc, cb) {\n    for (let i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 97) chunk[i] = 122 // swap 'a' for 'z'\n    }\n    this.push(chunk)\n    cb()\n  }))\n  .pipe(fs.createWriteStream('out.txt'))\n```\n\n### `objectTransform()`\n\n```\nobjectTransform([options], transformFn[, flushFn]) -> stream.Transform\n```\n\nLike `transform`, with `objectMode: true` enabled by default. Most async/async-generator use cases want this.\n\n### `transformer()`\n\n```\ntransformer([options], transformFn[, flushFn]) -> (overrideOptions?) -> stream.Transform\n```\n\nReturns 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.\n\n```js\nconst Counter = transformer({ objectMode: true }, function (chunk, _enc, cb) {\n  this.count = (this.count || 0) + 1\n  this.push(chunk)\n  cb()\n})\n\nconst a = Counter()\nconst b = new Counter({ highWaterMark: 32 })  // override per-call\n```\n\n### Composing pipelines\n\nFor 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).\n\n```js\nimport { pipeline } from 'node:stream/promises'\nimport { createReadStream, createWriteStream } from 'node:fs'\nimport { objectTransform } from 'through2'\n\nawait pipeline(\n  createReadStream('in.ndjson'),\n  objectTransform(async function * (source) {\n    let buf = ''\n    for await (const chunk of source) {\n      buf += chunk.toString()\n      const lines = buf.split('\\n')\n      buf = lines.pop()\n      for (const line of lines) yield JSON.parse(line)\n    }\n  }),\n  objectTransform(async (record) => record.active ? record : undefined),\n  objectTransform(async (record) => JSON.stringify(record) + '\\n'),\n  createWriteStream('out.ndjson')\n)\n```\n\n`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.\n\nA 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).\n\n### Default export (legacy)\n\nThe default export is `transform` with `.obj` and `.ctor` attached for back-compatibility:\n\n```js\nimport through2 from 'through2'\n\nthrough2(fn)        // === transform(fn)\nthrough2.obj(fn)    // === objectTransform(fn)\nthrough2.ctor(fn)   // === transformer(fn)\n```\n\n## Web Streams (`from 'through2/web'`)\n\n```js\nimport { transform } from 'through2/web'\n```\n\n### `transform()` (web)\n\n```\ntransform([transformFn][, flushFn]) -> TransformStream\n```\n\nReturns 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.\n\n```js\n// 1-to-many fan-out (controller form, stateless)\nconst tagged = transform((chunk, controller) => {\n  controller.enqueue({ kind: 'raw', value: chunk })\n  controller.enqueue({ kind: 'upper', value: chunk.toString().toUpperCase() })\n})\n\n// Splitter: cross-chunk state is needed (a line can span chunks). The async\n// generator form lets the buffer be a local variable; the classic controller\n// form would need closure state plus a flush handler.\nconst splitter = transform(async function * (source) {\n  let buf = ''\n  for await (const chunk of source) {\n    buf += chunk.toString()\n    const lines = buf.split('\\n')\n    buf = lines.pop()\n    for (const line of lines) yield line\n  }\n  if (buf) yield buf\n})\n\n// Async (1-to-1) with flush\nconst withTrailer = transform(\n  async (chunk) => chunk.toString().toUpperCase(),\n  (controller) => controller.enqueue('END')\n)\n\n// Pipe a fetch response through a transform\nawait response.body\n  .pipeThrough(transform(async (chunk) => chunk))\n  .pipeTo(destinationWritableStream)\n```\n\n### Implementation notes\n\nAt 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:\n\n- Backpressure works in both directions through `pipeThrough`.\n- Cancelling the consumer or aborting the producer cleans up your generator (its `finally` runs) and errors the other side.\n- Same behaviour in browsers, Node.js, Deno, Bun, and Cloudflare Workers.\n\nOne thing to note: `transform(asyncGenFn)` returns a `{ readable, writable }` pair rather than a `TransformStream` instance. `pipeThrough` and `pipeTo` accept it identically.\n\n## License\n\n**through2** is Copyright (c) Rod Vagg and additional contributors and licensed under the MIT license. See the included LICENSE file for more details.\n","publish_time":1782191082265,"_cnpm_publish_time":1782191082265,"dist-tags":{"1.0":"1.1.1","latest":"5.0.12"}}