在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异步/等待,而不是使用上面所示的回调,但同时仍然保持使用流的效率?
发布于 2015-11-08 22:30:40
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);
}());发布于 2018-11-12 11:49:52
如果使用节点版本>= v10.0.0,则可以使用stream.pipeline和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);发布于 2021-01-28 14:14:42
节点V15现在在流/许诺中有一个混杂的管道。这是最干净、最正式的方式。
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);我们都应该感谢它在这里所做的工作:
这个管道是Node.JS最强大的特性之一。让它完全异步并不容易。现在我们有了。
https://stackoverflow.com/questions/33599688
复制相似问题