https://github.com/socketcluster/consumable-stream
Readable async iterable stream.
https://github.com/socketcluster/consumable-stream
Last synced: 15 days ago
JSON representation
Readable async iterable stream.
- Host: GitHub
- URL: https://github.com/socketcluster/consumable-stream
- Owner: SocketCluster
- License: mit
- Created: 2018-11-18T17:01:40.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-09-06T19:50:03.000Z (over 2 years ago)
- Last Synced: 2025-07-27T06:42:15.351Z (8 months ago)
- Language: JavaScript
- Homepage:
- Size: 17.6 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# consumable-stream
A readable stream which can be iterated over using a for-await-of loop or using a while loop with await inside.
The `ConsumableStream` constructor is an abstract class which must be subclassed. Its `next()` and `createConsumer()` methods must be overriden.
For a concrete subclass of `ConsumableStream`, see `WritableConsumableStream`: https://github.com/SocketCluster/writable-consumable-stream
## Installation
```
npm install consumable-stream
```
## Usage
The `ConsumableStream` class exposes the following methods:
- `[Symbol.asyncIterator]`: Makes the instance iterable using a for-await-of loop.
- `next`: Returns a `Promise` which will resolve an object in the form `{value: data, done: boolean}` whenever some data is received or when the stream ends.
- `once`: Similar to `next()` except that the resolved value will be the raw data and it will not resolve when the stream ends. Note that once `once()` is called, it cannot be cancelled; the affected closure will stay in memory until either `once()` resolves or until the stream is ended or garbage collected.
```js
// Consume data objects from consumableStream as they are written to the stream.
(async () => {
for await (let data of consumableStream) {
console.log(data);
}
})();
// Consume only the next data object which is written to the stream.
(async () => {
let data = await consumableStream.once();
console.log(data);
})();
```