问题:
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.