2015-11-08 26 views
11

https://stackoverflow.com/a/18658613/779159是如何使用內置加密庫和流計算文件的md5的示例。如何使用ES8異步/等待與流?

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 /等待而不是使用回調如上可見,但同時仍保持使用流的效率?

+1

'異步/ await'也不過是承諾語法層面的支持。如果您可以將此代碼放在承諾中,那麼您就完成了。 –

回答

28

async/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 
}); 

現在你可以等待這一承諾:

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