【发布时间】:2016-02-09 13:00:17
【问题描述】:
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 而不是使用上面看到的回调,同时仍然保持使用流的效率?
【问题讨论】:
-
async/await只不过是对 Promise 的语法级支持。如果你可以把这段代码放在一个 Promise 中,那么你就完成了。 -
Node.js 10.x 支持使用
for-await-of读取流 (nodejs.org/docs/latest-v10.x/api/…) 但我认为这不是您的问题的正确概念。留给其他可能会遇到可能会有所帮助的情况的人。
标签: javascript node.js async-await ecmascript-2017