Javascript 如何在流中使用 ES8 async/await?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33599688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:15:57  来源:igfitidea点击:

How to use ES8 async/await with streams?

javascriptnode.jsasync-awaitecmascript-2017

提问by user779159

In https://stackoverflow.com/a/18658613/779159is an example of how to calculate the md5 of a file using the built-in crypto library and streams.

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

But is it possible to convert this to using ES8 async/await instead of using the callback as seen above, but while still keeping the efficiency of using streams?

但是是否可以将其转换为使用 ES8 async/await 而不是使用上面看到的回调,同时仍然保持使用流的效率?

回答by Bergi

async/awaitonly works with promises, not with streams. There are ideas to make an extra stream-like data type that would get its own syntax, but those are highly experimental if at all and I won't go into details.

async/await仅适用于承诺,不适用于流。有一些想法可以创建一个额外的类似流的数据类型,以获得自己的语法,但如果有的话,这些都是高度实验性的,我不会详细介绍。

Anyway, your callback is only waiting for the end of the stream, which is a perfect fit for a promise. You'd just have to wrap the stream:

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

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

Now you can await that promise:

现在你可以等待那个承诺:

(async function() {
    let sha1sum = await end;
    console.log(sha1sum);
}());

回答by shusson

If you are using node version >= v10.0.0 then you can use stream.pipelineand util.promisify.

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

回答by Ronnie Royston

Something like this works:

像这样的工作:

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