[英]Why does the filestream function not end
I wrote the following code to create a hash of a file: 我编写了以下代码来创建文件的哈希:
function hashFile(filePath){
try{
// Setup hash
var hash = crypto.createHash('sha256');
hash.setEncoding('hex');
// Setup filestream
var fileStream = fs.createReadStream(filePath);
fileStream.pipe(hash, { end: false });
fileStream.on('end', function () {
// Get the hash
hash.end();
var thisHash = String(hash.read());
});
}catch (err) {
console.log( "Error thrown : " + err );
return;
}
}
This worked just fine until I threw some smaller files at it. 这工作得很好,直到我扔了一些较小的文件。 When I did this the function would just hang.
当我这样做时,该功能就会挂起。 The
filestream.on('end')
callback would never happen. filestream.on('end')
回调永远不会发生。
I rewrote it to not use createReadStream: 我重写它不使用createReadStream:
function hashFile(filePath){
try{
fs.readFile(filePath, function (err, data) {
// Make the hash
var thisHash = crypto
.createHash('sha256')
.update(data, 'utf8')
.digest( 'hex');
console.log(thisHash);
});
}catch (err) {
console.log( "Error: " + err );
return;
}
}
This code works just fine, except it's incredibly slow on files that are a few MB or larger. 这段代码工作得很好,除了它在几MB或更大的文件上非常慢。
My question is why doesn't the first function work on small files? 我的问题是为什么第一个函数不适用于小文件?
So after searching for the answer all evening, I figured it out 15 min after writing this post. 所以在整个晚上寻找答案之后,我在写完这篇文章后15分钟就知道了。 The 'end' callback needs to configured before calling pipe:
在调用管道之前需要配置'end'回调:
var fileStream = fs.createReadStream(filePath);
var hash = crypto.createHash('sha256');
hash.setEncoding('hex');
fileStream.on('end', function () {
hash.end();
console.log(hash.read());
});
fileStream.pipe(hash);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.