102

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 を使用するように変換することは可能ですか?

4

6 に答える 6

130

async/awaitストリームではなく、promise でのみ機能します。独自の構文を取得する追加のストリームのようなデータ型を作成するアイデアがありますが、それらは非常に実験的なものであり、詳細には触れません。

とにかく、あなたのコールバックはストリームの終了を待っているだけです。これはプロミスにぴったりです。ストリームをラップするだけです:

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);
}());
于 2015-11-08T22:30:40.070 に答える
82

ノード バージョン >= 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);
于 2018-11-12T11:49:52.890 に答える