0

我使用request 带有crypto. 似乎request实现了旧stream协议,并且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.

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

4

1 回答 1

0

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

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

Stream1 实现需要 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

于 2017-04-14T15:25:02.387 回答