2015-11-08 9 views
11

https://stackoverflow.com/a/18658613/779159は、組み込みの暗号ライブラリとストリームを使用してファイルのmd5を計算する方法の例です。ES8 async/streams with a streamsを使用するには?

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

しかし、代わりに、上記見たコールバックを使用する非同期/のawait ES8を使用してこれを変換することが可能であるが、依然としてストリームの利用効率を維持しながら?

+1

'非同期/ await'が約束の構文レベルでのサポート以外の何ものでもありません:

var fd = fs.createReadStream('/some/file/name.txt'); var hash = crypto.createHash('sha1'); hash.setEncoding('hex'); fd.on('end', function() { hash.end(); }); // read all file and pipe it (write it) to the hash object fd.pipe(hash); var end = new Promise(function(resolve, reject) { fd.on('end',()=>resolve(hash.read())); fd.on('error', reject); // or something like that }); 

は今、あなたはその約束を待つことができます。あなただけのストリームをラップする必要があると思います。このコードを約束の中に置くことができれば、あなたは完了です。 –

答えて

28

async/awaitは、ストリームではなく、約束でのみ動作します。独自の構文を持つような余分なストリームのようなデータ型を作成するアイデアはありますが、これらは非常に実験的なものであり、詳細には触れません。

とにかく、あなたのコールバックはストリームの終わりを待っているだけです。これは、約束事に最適です。

(async function() { 
    let sha1sum = await end; 
    console.log(sha1sum); 
}()); 
関連する問題