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

问题描述 投票:32回答:3

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 /伺机而不是使用回调如上可见,但同时仍保持使用流的效率?

javascript node.js async-await ecmascript-2017
3个回答
70
投票

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

13
投票

如果您使用的节点版本> = 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);

3
投票

像这样的工作:

for (var res of fetchResponses){ //node-fetch package responses
    const dest = fs.createWriteStream(filePath,{flags:'a'});
    totalBytes += Number(res.headers.get('content-length'));
    await new Promise((resolve, reject) => {
        res.body.pipe(dest);
        res.body.on("error", (err) => {
            reject(err);
        });
        dest.on("finish", function() {
            resolve();
        });
    });         
}
© www.soinside.com 2019 - 2024. All rights reserved.