Node: Allow to await writable streams

Created on 1 Mar 2018  路  3Comments  路  Source: nodejs/node

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

promises stream

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

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);
})();

All 3 comments

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);
})();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

willnwhite picture willnwhite  路  3Comments

dfahlander picture dfahlander  路  3Comments

srl295 picture srl295  路  3Comments

akdor1154 picture akdor1154  路  3Comments

vsemozhetbyt picture vsemozhetbyt  路  3Comments