如何将 ES8 async/await 与流一起使用?

新手上路,请多包涵

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 async/await 而不是使用上面看到的回调,同时仍然保持使用流的效率?

原文由 user779159 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

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

原文由 Bergi 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您使用的节点版本 >= v10.0.0 那么您可以使用 stream.pipelineutil.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);

原文由 shusson 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题