简体   繁体   English

为什么文件流功能没有结束

[英]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.

相关问题 为什么 setTimeout 0 没有在函数结束时执行 - Why does the setTimeout 0 not executing at the end of the function 为什么在最后调用回调函数,以及如何测试该函数? - Why does the callback function called at the end and how to test the function? 为什么javascript让您在函数参数的末尾添加逗号? - Why does javascript let you add comma in the end of function parameters? 该递归函数如何结束? - How does this recursive function end? 为什么我的后端函数循环,从而使我的GET ajax调用失败? - Why does my back-end function loops, thus making my GET ajax call fail? 为什么我的 function 在声明返回时没有结束(Node.js 和 Express.js) - Why does my function not end when a return is stated (Node.js and Express.js) 为什么 Promise.prototype.then 允许跳过拒绝 function 并在末尾允许逗号? - Why does Promise.prototype.then allow skipping reject function and allow comma at the end? 异步函数不等待 await 函数结束 - Async function does not wait for await function to end 为什么这会在Javascript中以无限循环结束? - Why does this end up in an infinite loop in Javascript? 为什么 repl.it 最后记录未定义? - Why does repl.it log undefined at the end?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM