小编典典

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

node.js

示例了如何使用内置的加密库和流来计算文件的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异步/等待而不是使用上述回调,但仍保持使用流的效率?


阅读 261

收藏
2020-07-07

共1个答案

小编典典

async/
await仅适用于promise,不适用于流。有一些想法可以制作一种类似流的额外数据类型,该数据类型将具有自己的语法,但是如果有的话,这些想法是高度实验性的,我将不赘述。

无论如何,您的回调仅等待流结束,这非常适合兑现承诺。您只需要包装流:

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