With async iterators, we can use synchronous-looking code to consume readable streams.
There is no equivalent for writable streams in Node core.
Example use case:
const fs = require('fs');
const zlib = require('zlib');
(async () => {
const read = fs.createReadStream('data.txt.gz');
const gunzip = zlib.createGunzip();
const write = fs.createWriteStream('data.txt');
await read.pipe(gunzip).pipe(write);
})();
This would resolve when write
ends or reject if an error occurs.
Prior art:
/cc @nodejs/streams @mcollina
This is currently not possible because of how error handling work in streams.
However, wrapping #13506 (stream.pump
) in a promise should be simple to do. I think we should work on landing that first, and then adding a promisified version of that too (or util.promisify()
).
Will be possible with the new pipeline api (based on pump) in https://github.com/nodejs/node/pull/19828 and util.promisify, assuming it lands at it's current form
const stream = require('stream')
(async () => {
const pipeline = util.promisify(stream.pipeline)
const read = fs.createReadStream('data.txt.gz');
const gunzip = zlib.createGunzip();
const write = fs.createWriteStream('data.txt');
await pipeline(read, gunzip, write);
})();
Most helpful comment
Will be possible with the new pipeline api (based on pump) in https://github.com/nodejs/node/pull/19828 and util.promisify, assuming it lands at it's current form