Convert streaming iterables to Node.js streams
npm i it-to-stream
const toStream = require('it-to-stream')
// A streaming iterable "source" is just an (async) iterable
const source = (async function * () {
for (const value of [1, 2, 3, 4]) yield Buffer.from(value.toString())
})()
const readable = toStream.readable(source)
// Now we have a readable stream, we can consume it by
readable.on('data', console.log)
// or
readable.pipe(writable)
// or
pipeline(readable, writable, err => console.log(err || 'done'))
// A streaming iterable "sink" is an (async) function that takes a "source"
// and consumes it.
const sink = async source => {
for await (const chunk of source) {
console.log(chunk.toString())
}
}
const writable = toStream.writable(sink)
// Now we have a writable stream, we can pipe to it
fs.createReadStream('/path/to/file').pipe(writable)
// A streaming iterable "transform" is a function that takes a "source" and
// returns a "source".
const transform = source => (async function * () {
for await (const chunk of source) {
// Replace all space characters with dashes
yield Buffer.from(chunk.toString().replace(/ /g, '-'))
}
})()
const transform = toStream.transform(transform)
// Now we have a transform stream, we can pipe to and from it
fs.createReadStream('/path/to/file')
.pipe(transform)
.pipe(fs.createWriteStream('/path/to/file2'))
const toStream = require('it-to-stream')
Convert a source iterable to a Readable
stream.
options
are passed directly to the Readable
constructor.
Convert a sink iterable to a Writable
stream.
options
are passed directly to the Writable
constructor.
Convert a transform iterable to a Transform
stream.
options
are passed directly to the Transform
constructor.
Convert a duplex iterable to a Duplex
stream.
options
are passed directly to the Duplex
constructor.
stream-to-it
Convert Node.js streams to streaming iterablesit-pipe
Utility to "pipe" async iterables together
Feel free to dive in! Open an issue or submit PRs.
MIT © Alan Shaw