├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── license ├── media └── logo.jpg ├── package.json ├── readme.md └── test.js /.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 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.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 | - 22 14 | - 20 15 | - 18 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: actions/setup-node@v4 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | - run: npm install 22 | - run: npm test 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import {type Readable, type PassThrough} from 'node:stream'; 2 | 3 | /** 4 | Creates a function that returns independent streams for each consumer. 5 | 6 | @param sourceStream - The source stream to multicast. 7 | @returns A function that returns a new `PassThrough` stream for each consumer. 8 | */ 9 | export default function multicastStream(sourceStream: Readable): () => PassThrough; 10 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import {PassThrough} from 'node:stream'; 2 | 3 | export default function multicastStream(sourceStream) { 4 | const consumers = new Set(); 5 | let isStarted = false; 6 | 7 | const start = () => { 8 | if (isStarted) { 9 | return; 10 | } 11 | 12 | isStarted = true; 13 | 14 | sourceStream.on('data', chunk => { 15 | for (const consumer of consumers) { 16 | consumer.write(chunk); 17 | } 18 | }); 19 | 20 | sourceStream.on('end', () => { 21 | for (const consumer of consumers) { 22 | consumer.end(); 23 | } 24 | }); 25 | 26 | sourceStream.on('error', error => { 27 | for (const consumer of consumers) { 28 | consumer.destroy(error); 29 | } 30 | }); 31 | }; 32 | 33 | return () => { 34 | const consumer = new PassThrough(); 35 | consumers.add(consumer); 36 | 37 | consumer.on('close', () => { 38 | consumers.delete(consumer); 39 | }); 40 | 41 | if (!isStarted) { 42 | start(); 43 | } 44 | 45 | return consumer; 46 | }; 47 | } 48 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /media/logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sindresorhus/multicast-stream/41ac1f2c928ff9a8f38cd9ee79356bdd3b54868e/media/logo.jpg -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "multicast-stream", 3 | "version": "0.1.0", 4 | "description": "Create a multicast stream that lets multiple consumers independently read the same data", 5 | "license": "MIT", 6 | "repository": "sindresorhus/multicast-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": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18.19" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsc index.d.ts" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "multicast", 31 | "broadcast", 32 | "split", 33 | "stream", 34 | "readable", 35 | "passthrough", 36 | "multi", 37 | "multiple", 38 | "consumers", 39 | "consumption", 40 | "streaming", 41 | "streams", 42 | "clone" 43 | ], 44 | "devDependencies": { 45 | "ava": "^6.1.3", 46 | "typescript": "^5.5.4", 47 | "xo": "^0.59.3" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

2 | multicast-stream logo 3 |

4 | 5 | > Create a multicast stream that lets multiple consumers independently read the same data 6 | 7 | ## Install 8 | 9 | ```sh 10 | npm install multicast-stream 11 | ``` 12 | 13 | ## Usage 14 | 15 | **Without this package** 16 | 17 | Using [`Readable#text()`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) on a stream can only work with a single consumer. If you try to read the stream with multiple consumers, it will be empty as the stream can only be read once. 18 | 19 | ```js 20 | import {Readable} from 'node:stream'; 21 | import {text} from 'node:stream/consumers'; 22 | 23 | const sourceStream = Readable.from(['Hello', ' ', 'World']); 24 | const [result1, result2] = await Promise.all([text(sourceStream), text(sourceStream)]); 25 | 26 | console.log(result1); // 'Hello World' 27 | console.log(result2); // '' 28 | ``` 29 | 30 | **With this package** 31 | 32 | This package allows multiple consumers to independently read the same data from a single source stream. 33 | 34 | ```js 35 | import {Readable} from 'node:stream'; 36 | import {text} from 'node:stream/consumers'; 37 | import multicastStream from 'multicast-stream'; 38 | 39 | const sourceStream = Readable.from(['Hello', ' ', 'World']); 40 | const createConsumer = multicastStream(sourceStream); 41 | 42 | const consumer1 = createConsumer(); 43 | const consumer2 = createConsumer(); 44 | 45 | const [result1, result2] = await Promise.all([text(consumer1), text(consumer2)]); 46 | 47 | console.log(result1); // 'Hello World' 48 | console.log(result2); // 'Hello World' 49 | ``` 50 | 51 | ## API 52 | 53 | ### `multicastStream(sourceStream)` 54 | 55 | Creates a function that returns independent streams for each consumer. 56 | 57 | #### Parameters 58 | 59 | - `sourceStream` (`Readable`): The source stream to multicast. 60 | 61 | #### Returns 62 | 63 | - `() => PassThrough`: A function that returns a new `PassThrough` stream for each consumer. 64 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import {Readable} from 'node:stream'; 2 | import {text} from 'node:stream/consumers'; 3 | import test from 'ava'; 4 | import multicastStream from './index.js'; 5 | 6 | const createFixtureStream = () => Readable.from(['Hello', ' ', 'World']); 7 | 8 | test('creates independent consumers', async t => { 9 | const sourceStream = createFixtureStream(); 10 | const createConsumer = multicastStream(sourceStream); 11 | 12 | const consumer1 = createConsumer(); 13 | const consumer2 = createConsumer(); 14 | 15 | const [result1, result2] = await Promise.all([ 16 | text(consumer1), 17 | text(consumer2), 18 | ]); 19 | 20 | t.is(result1, 'Hello World'); 21 | t.is(result2, 'Hello World'); 22 | }); 23 | 24 | test('handles large amount of data', async t => { 25 | const fixtureSize = 1_000_000; 26 | const largeData = Buffer.from('x'.repeat(fixtureSize)); 27 | const sourceStream = Readable.from([largeData]); 28 | 29 | const createConsumer = multicastStream(sourceStream); 30 | 31 | const consumer1 = createConsumer(); 32 | const consumer2 = createConsumer(); 33 | 34 | const [result1, result2] = await Promise.all([ 35 | text(consumer1), 36 | text(consumer2), 37 | ]); 38 | 39 | t.is(result1.length, fixtureSize); 40 | t.is(result2.length, fixtureSize); 41 | t.is(result1, largeData.toString()); 42 | t.is(result2, largeData.toString()); 43 | }); 44 | 45 | test('is lazy and only starts consuming when first consumer reads', async t => { 46 | let consumed = false; 47 | const sourceStream = new Readable({ 48 | read() { 49 | consumed = true; 50 | this.push('data'); 51 | this.push(null); 52 | }, 53 | }); 54 | 55 | const createConsumer = multicastStream(sourceStream); 56 | 57 | t.false(consumed, 'Source stream should not be consumed before any consumer reads'); 58 | 59 | const consumer = createConsumer(); 60 | t.false(consumed, 'Source stream should not be consumed when consumer is created'); 61 | 62 | // Use text() to start consuming the stream 63 | const result = await text(consumer); 64 | 65 | t.true(consumed, 'Source stream should be consumed when consumer starts reading'); 66 | t.is(result, 'data', 'Consumer should receive the correct data'); 67 | }); 68 | 69 | test('handles errors from source stream', async t => { 70 | const sourceStream = new Readable({ 71 | read() { 72 | this.emit('error', new Error('Source stream error')); 73 | }, 74 | }); 75 | 76 | const createConsumer = multicastStream(sourceStream); 77 | const consumer = createConsumer(); 78 | 79 | await t.throwsAsync(async () => { 80 | await text(consumer); 81 | }, {message: 'Source stream error'}); 82 | }); 83 | 84 | test('handles source stream ending', async t => { 85 | const sourceStream = Readable.from(['data']); 86 | const createConsumer = multicastStream(sourceStream); 87 | const consumer = createConsumer(); 88 | 89 | const result = await text(consumer); 90 | t.is(result, 'data', 'Should receive correct data'); 91 | 92 | // Try to read from the ended stream 93 | const endedResult = await text(consumer); 94 | t.is(endedResult, '', 'Should return empty string for ended stream'); 95 | }); 96 | 97 | test('handles source stream destruction', async t => { 98 | const sourceStream = Readable.from(['data']); 99 | const createConsumer = multicastStream(sourceStream); 100 | const consumer1 = createConsumer(); 101 | const consumer2 = createConsumer(); 102 | 103 | const consumer1ErrorPromise = new Promise(resolve => { 104 | consumer1.on('error', error => { 105 | resolve(error); 106 | }); 107 | }); 108 | 109 | const consumer2ErrorPromise = new Promise(resolve => { 110 | consumer2.on('error', error => { 111 | resolve(error); 112 | }); 113 | }); 114 | 115 | // Destroy the source stream 116 | sourceStream.destroy(new Error('Stream destroyed')); 117 | 118 | // Await the errors from the consumers 119 | const [error1, error2] = await Promise.all([consumer1ErrorPromise, consumer2ErrorPromise]); 120 | 121 | // Check the error messages 122 | t.is(error1.message, 'Stream destroyed'); 123 | t.is(error2.message, 'Stream destroyed'); 124 | }); 125 | 126 | test('handles consumer error without affecting others', async t => { 127 | const createConsumer = multicastStream(createFixtureStream()); 128 | const consumer1 = createConsumer(); 129 | const consumer2 = createConsumer(); 130 | const consumer2Text = text(consumer2); 131 | 132 | // Simulate an error in consumer1 133 | consumer1.on('error', () => {}); 134 | consumer1.destroy(new Error('Consumer error')); 135 | 136 | // Ensure consumer2 is not affected and can still read 137 | t.is(await consumer2Text, 'Hello World'); 138 | }); 139 | --------------------------------------------------------------------------------