https://github.com/borewit/t-readable
Split a readable-stream into 2 or more readable-streams
https://github.com/borewit/t-readable
Last synced: 9 months ago
JSON representation
Split a readable-stream into 2 or more readable-streams
- Host: GitHub
- URL: https://github.com/borewit/t-readable
- Owner: Borewit
- Created: 2019-12-31T12:58:56.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2023-02-03T03:23:25.000Z (almost 3 years ago)
- Last Synced: 2024-10-29T16:57:50.223Z (about 1 year ago)
- Language: TypeScript
- Size: 559 KB
- Stars: 1
- Watchers: 3
- Forks: 2
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[](https://travis-ci.org/Borewit/t-readable)
[](https://npmjs.org/package/t-readable)
[](https://npmcharts.com/compare/t-readable?start=1200&interval=30)
[](https://lgtm.com/projects/g/Borewit/t-readable/alerts/)
[](https://lgtm.com/projects/g/Borewit/t-readable/context:javascript)
# t-readable
Split one [_readable stream_](https://nodejs.org/api/stream.html#stream_readable_streams) into multiple [_readable streams_](https://nodejs.org/api/stream.html#stream_readable_streams).
## Installation
Using [npm](https://www.npmjs.com/get-npm):
```sh
npm install t-readable
```
or [yarn](https://yarnpkg.com/):
```sh
yarn add t-readable
```
## Usage
```js
const { tee } = require('t-readable');
const got = require('got');
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
/**
* Counts the number of bytes in the givent stream
* @param readable {stream.Readable} - Readable stream
* @return {Promise} - Number of bytes until the end of stream is reached
*/
async function countBytes(readable) {
let bytesRead = 0;
return new Promise((resolve, reject) => {
readable.on('data', chunk => {
bytesRead += chunk.length;
});
readable.on('end', () => {
resolve(bytesRead);
});
readable.on('error', error => {
reject(error);
});
});
}
(async () => {
const stream = got.stream(url); // stream is an instance of class stream.Readable
const teedStreams = tee(stream);
// Count the number of bytes received in each teed stream
const counts = await Promise.all(teedStreams.map(readable => countBytes(readable)));
console.log('Counts: ' + counts.join(', ')); // Counts: 27661, 27661
})();
```