【问题标题】:Why crypto.createHash() is not writable until setEncoding() is called?为什么在调用 setEncoding() 之前 crypto.createHash() 不可写?
【发布时间】:2017-04-14 23:25:02
【问题描述】:

我使用request packagecrypto。似乎request 实现了旧的stream 协议和don't write 任何数据到管道目标,直到它是writable

Stream.prototype.pipe = function(dest, options) {
  var source = this;

  function ondata(chunk) {
    if (dest.writable) {
      if (false === dest.write(chunk) && source.pause) {
        source.pause();
      }
    }
  }
...

所以,如果我使用下一个代码:

const crypto = require('crypto'); 
const request = require('request');

var hasher = crypto.createHash('sha256'); 
// Uncomment the line below to fix!
// hasher.setEncoding('hex');
console.log(hasher.writable); 
request('http://ya.ru').pipe(hasher).on('finish', function() {
    console.log('Hash is', hasher.read()); 
});

它产生sha256('')(即从空值)。但是当我使用hasher.setEncoding('hex') 时,代码会生成sha256(<response_body>),而hasher.writable 会生成true

我不明白这样做的原因是什么?文档中在哪里说明了这一点?

【问题讨论】:

    标签: node.js node-request node-crypto node-streams


    【解决方案1】:

    最后,Node.js 中出现了bug。这是重现它的更小的代码示例:

    var hasher = crypto.createHash('sha256'); 
    const _ = hasher._writableState;  // we don't even have to call .setEnconding() here
    console.log(hasher.writable);
    

    Stream1 实现 required this.writable 在目标流中为真。

    Stream.prototype.pipe = function(dest, options) {
      var source = this;
    
      function ondata(chunk) {
        if (dest.writable) {
          if (false === dest.write(chunk) && source.pause) {
            source.pause();
          }
        }
      }
    
      source.on('data', ondata);
      ...
    

    调用hasher.setEncoding('hex')(或任何其他对this._writableState 的访问)触发了对流的实际构造函数的调用。在它之前this.writableundefined

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-31
      • 2015-09-27
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      相关资源
      最近更新 更多