├── .npmrc ├── .gitattributes ├── .gitignore ├── .editorconfig ├── index.test-d.ts ├── .github └── workflows │ └── main.yml ├── package.json ├── index.d.ts ├── license ├── index.js ├── test.js └── readme.md /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {type Transform as TransformStream} from 'node:stream'; 2 | import {expectType} from 'tsd'; 3 | import transformStream from './index.js'; 4 | 5 | expectType(transformStream(async chunk => chunk)); 6 | 7 | transformStream({objectMode: true}, async chunk => chunk); 8 | 9 | transformStream(async () => {}, async function * () { // eslint-disable-line @typescript-eslint/no-empty-function 10 | yield 'x'; 11 | }); 12 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 18 14 | - 16 15 | steps: 16 | - uses: actions/checkout@v3 17 | - uses: actions/setup-node@v3 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "easy-transform-stream", 3 | "version": "1.0.1", 4 | "description": "Create a transform stream using await instead of callbacks", 5 | "license": "MIT", 6 | "repository": "sindresorhus/easy-transform-stream", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": "./index.js", 15 | "types": "./index.d.ts", 16 | "engines": { 17 | "node": ">=14.16" 18 | }, 19 | "scripts": { 20 | "test": "xo && ava && tsd" 21 | }, 22 | "files": [ 23 | "index.js", 24 | "index.d.ts" 25 | ], 26 | "keywords": [ 27 | "stream", 28 | "transform", 29 | "async", 30 | "function", 31 | "await", 32 | "through" 33 | ], 34 | "devDependencies": { 35 | "ava": "^4.3.0", 36 | "delay": "^5.0.0", 37 | "get-stream": "^6.0.1", 38 | "tsd": "^0.20.0", 39 | "xo": "^0.54.2" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import {type Transform as TransformStream, type TransformOptions} from 'node:stream'; 2 | 3 | export type Options = Omit; 4 | 5 | /** 6 | Receives each chunk and is expected to return a transformed chunk. 7 | */ 8 | export type Transformer = (chunk: unknown, encoding: BufferEncoding, stream: TransformStream) => Promise; 9 | 10 | /** 11 | Yield additional chunks at the end of the stream. 12 | */ 13 | export type Flusher = () => AsyncGenerator; 14 | 15 | /** 16 | Create a transform stream using await instead of callbacks. 17 | 18 | @example 19 | ``` 20 | import transformStream from 'easy-transform-stream'; 21 | 22 | const stream = transformStream(async chunk => { 23 | const newChunk = await modifyChunk(chunk); 24 | return newChunk; 25 | }); 26 | ``` 27 | */ 28 | export default function transformStream(transformer: Transformer, flusher?: Flusher): TransformStream; 29 | export default function transformStream(options: Options, transformer: Transformer, flusher?: Flusher): TransformStream; 30 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import {Transform as TransformStream} from 'node:stream'; 2 | 3 | export default function transformStream(options = {}, transformer, flusher) { 4 | if (typeof options === 'function') { 5 | flusher = transformer; 6 | transformer = options; 7 | } 8 | 9 | return new TransformStream({ 10 | ...options, 11 | transform(chunk, encoding, callback) { 12 | (async () => { 13 | try { 14 | const value = await transformer(chunk, encoding, this); 15 | 16 | // If the callback throws, we don't want to cause an infinite recursion. 17 | try { 18 | callback(undefined, value); 19 | } catch {} 20 | } catch (error) { 21 | callback(error); 22 | } 23 | })(); 24 | }, 25 | flush(callback) { 26 | if (typeof flusher !== 'function') { 27 | callback(); 28 | return; 29 | } 30 | 31 | (async () => { 32 | try { 33 | for await (const chunk of flusher(this)) { 34 | this.push(chunk); 35 | } 36 | 37 | // If the callback throws, we don't want to cause an infinite recursion. 38 | try { 39 | callback(); 40 | } catch {} 41 | } catch (error) { 42 | callback(error); 43 | } 44 | })(); 45 | }, 46 | }); 47 | } 48 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import {promisify} from 'node:util'; 2 | import {Readable as ReadableStream, PassThrough as PassThroughStream, pipeline} from 'node:stream'; 3 | import test from 'ava'; 4 | import delay from 'delay'; 5 | import getStream from 'get-stream'; 6 | import transformStream from './index.js'; 7 | 8 | const pipelinePromise = promisify(pipeline); 9 | 10 | test('transform', async t => { 11 | const sourceStream = ReadableStream.from([...'abc']); 12 | const destinationStream = new PassThroughStream(); 13 | 14 | sourceStream.setEncoding('utf8'); 15 | 16 | let callCount = 0; 17 | 18 | await pipelinePromise( 19 | sourceStream, 20 | transformStream({decodeStrings: false}, async chunk => { 21 | callCount++; 22 | await delay(200); 23 | return chunk.toUpperCase(); 24 | }), 25 | destinationStream, 26 | ); 27 | 28 | t.is(callCount, 3); 29 | t.is(await getStream(destinationStream), 'ABC'); 30 | }); 31 | 32 | test('flush', async t => { 33 | const sourceStream = ReadableStream.from([...'abc']); 34 | const destinationStream = new PassThroughStream(); 35 | 36 | sourceStream.setEncoding('utf8'); 37 | 38 | await pipelinePromise( 39 | sourceStream, 40 | transformStream(chunk => chunk, async function * () { 41 | yield 'd'; 42 | yield 'e'; 43 | }), 44 | destinationStream, 45 | ); 46 | 47 | t.is(await getStream(destinationStream), 'abcde'); 48 | }); 49 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # easy-transform-stream 2 | 3 | > Create a transform stream using await instead of callbacks 4 | 5 | The built-in [`stream.Transform` constructor](https://nodejs.org/api/stream.html#class-streamtransform) forces you to deal with a callback interface. It's much nicer to just be able to await and return a value. 6 | 7 | This package can be thought of as a modern version of [`through2`](https://github.com/rvagg/through2). 8 | 9 | ## Install 10 | 11 | ```sh 12 | npm install easy-transform-stream 13 | ``` 14 | 15 | ## Usage 16 | 17 | ```js 18 | import transformStream from 'easy-transform-stream'; 19 | 20 | const stream = transformStream(async chunk => { 21 | const newChunk = await modifyChunk(chunk); 22 | return newChunk; 23 | }); 24 | ``` 25 | 26 | ## API 27 | 28 | ### easyTransformStream(transformer, flusher?) 29 | ### easyTransformStream(options, transformer, flusher?) 30 | 31 | #### transformer(chunk, encoding, stream) 32 | 33 | Type: Async function 34 | 35 | Receives each chunk and is expected to return a transformed chunk. 36 | 37 | #### flusher(stream) 38 | 39 | Type: Async generator function 40 | 41 | Yield additional chunks at the end of the stream. 42 | 43 | #### options 44 | 45 | Type: `object` 46 | 47 | Same as the [options for `stream.Transform`](https://nodejs.org/api/stream.html#new-streamtransformoptions), except for `transform` and `flush`. 48 | 49 | ## Related 50 | 51 | - [get-stream](https://github.com/sindresorhus/get-stream) - Get a stream as a string, buffer, or array 52 | --------------------------------------------------------------------------------