how to get outputStream chunks in sync mode?

问题: is there a way to convert stream to buffer in sync mode? I need to get it like: let newBuffer = outputStream.getDataSync(); rather than outputStream.on('data'... like...

问题:

is there a way to convert stream to buffer in sync mode? I need to get it like:

let newBuffer = outputStream.getDataSync();

rather than outputStream.on('data'... like below

let newBuffer = convertStream(outputStream);

function convertStream(strm) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    strm.on('data', (chunk) => {
      chunks.push(chunk);
    }).on('end', () => {
      resolve(Buffer.concat(chunks));
    }).on('error', (err) => {
      reject(err);
    });
  });
}

I cannot use await for convertStream because the function I call it from is not async


回答1:

You could potentially use await by wrapping the the call to convertStream() in an Immediately Invoked Async Function Expression.

function foo() {
  return Promise.resolve('bar');
}

(async function() { console.log(await foo()); })();


回答2:

A Stream is a flow of data. You cannot get a buffer synchronously, as the data in the stream might already started flowing, or will arrive somewhen.

I cannot use await for convertStream because the function I call it from is not async

Then make that function you call from async?


回答3:

It is said that asynchrony is contagious: as soon as you have one asynchronous bit in your flow, all the dependent flow needs to be asynchronous. Streams are asynchronous by nature, so you can only simplify your code via synchronous-looking async-await.

BTW, the asynchronous iterator interface for streams may be the most concise way to do this.

  • 发表于 2019-02-17 15:46
  • 阅读 ( 187 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除