如何在流中使用 ES8异步/等待?

https://stackoverflow.com/a/18658613/779159中有一个例子,说明如何使用内置的加密库和流来计算文件的 md5。

var fs = require('fs');
var crypto = require('crypto');


// the file you want to get the hash
var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');


fd.on('end', function() {
hash.end();
console.log(hash.read()); // the desired sha1sum
});


// read all file and pipe it (write it) to the hash object
fd.pipe(hash);

但是,是否有可能将其转换为使用 ES8异步/等待,而不是使用上面看到的回调,同时仍然保持使用流的效率?

124209 次浏览

async/await只适用于承诺,不适用于流。有一些想法可以创建一个额外的类似于流的数据类型,它可以得到自己的语法,但是这些都是高度实验性的,如果有的话,我就不详细介绍了。

无论如何,您的回调只是在等待流的结束,这是一个完美的承诺。你只需要包住这条小溪:

var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
// read all file and pipe it (write it) to the hash object
fd.pipe(hash);


var end = new Promise(function(resolve, reject) {
hash.on('end', () => resolve(hash.read()));
fd.on('error', reject); // or something like that. might need to close `hash`
});

现在你可以等待这个承诺:

(async function() {
let sha1sum = await end;
console.log(sha1sum);
}());

如果使用的是 node version > = v10.0.0,那么可以使用 流,管道util.promisify

const fs = require('fs');
const crypto = require('crypto');
const util = require('util');
const stream = require('stream');


const pipeline = util.promisify(stream.pipeline);


const hash = crypto.createHash('sha1');
hash.setEncoding('hex');


async function run() {
await pipeline(
fs.createReadStream('/some/file/name.txt'),
hash
);
console.log('Pipeline succeeded');
}


run().catch(console.error);

像这样的东西是有用的:

for (var res of fetchResponses){ //node-fetch package responses
const dest = fs.createWriteStream(filePath,{flags:'a'});
totalBytes += Number(res.headers.get('content-length'));
await new Promise((resolve, reject) => {
res.body.pipe(dest);
res.body.on("error", (err) => {
reject(err);
});
dest.on("finish", function() {
resolve();
});
});
}

Node V15 now has a promisfiy pipeline in 信息流[承诺]. 这是最干净,最正式的方式。

const { pipeline } = require('stream/promises');


async function run() {
await pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz')
);
console.log('Pipeline succeeded.');
}


run().catch(console.error);

We all should appreciate how much works it's done here:

  • 捕获所有流中的错误。
  • 当出现错误时,销毁未完成的流。
  • 只有当最后一个可写流是 结束了时才返回。

This pipe thing is one of the most powerful feature Node.JS has. Making it fully async is not easy. Now we have it.

我会评论,但没有足够的声誉。

提醒一句: 如果您的应用程序正在传递流并执行异步/等待操作,请在等待之前非常小心地连接所有管道。您可能最终得到的流并不包含您认为它们所做的事情。这是最小的例子

const { PassThrough } = require('stream');


async function main() {
const initialStream = new PassThrough();


const otherStream = new PassThrough();
const data = [];
otherStream.on('data', dat => data.push(dat));
const resultOtherStreamPromise = new Promise(resolve => otherStream.on('end', () => { resolve(Buffer.concat(data)) }));


const yetAnotherStream = new PassThrough();
const data2 = [];
yetAnotherStream.on('data', dat => data2.push(dat));
const resultYetAnotherStreamPromise = new Promise(resolve => yetAnotherStream.on('end', () => { resolve(Buffer.concat(data2)) }));


initialStream.pipe(otherStream);
initialStream.write('some ');


await Promise.resolve(); // Completely unrelated await


initialStream.pipe(yetAnotherStream);
initialStream.end('data');
const [resultOtherStream, resultYetAnotherStream] = await Promise.all([
resultOtherStreamPromise,
resultYetAnotherStreamPromise,
]);


console.log('other stream:', resultOtherStream.toString()); // other stream: some data
console.log('yet another stream:', resultYetAnotherStream.toString()); // yet another stream: data
}
main();

2021年更新:

Node 文档中的新示例:

async function print(readable) {
readable.setEncoding('utf8');
let data = '';
for await (const chunk of readable) {
data += chunk;
}
console.log(data);
}

https://nodejs.org/api/stream.html#stream_readable_symbol_asynciterator