如何使用ES8asynchronous/等待与stream?

在https://stackoverflow.com/a/18658613/779159中是如何使用内置的encryption库和stream来计算文件的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); 

但是,有可能将此转换为使用ES8asynchronous/等待,而不是像上面看到的使用callback,但仍然保持使用stream的效率?

async / await只适用于承诺,不适用于stream。 有一些想法可以创build一个额外的类似于数据stream的数据types来获得自己的语法,但是这些数据types是非常实验性的,如果有的话我不会详细讨论。

无论如何,你的callback只是等待stream的结束,这是一个完美契合的承诺。 你只需要包装stream:

 var fd = fs.createReadStream('/some/file/name.txt'); var hash = crypto.createHash('sha1'); hash.setEncoding('hex'); fd.on('end', function() { hash.end(); }); // read all file and pipe it (write it) to the hash object fd.pipe(hash); var end = new Promise(function(resolve, reject) { fd.on('end', ()=>resolve(hash.read())); fd.on('error', reject); // or something like that }); 

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

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