目的地已满时如何暂停nodejs流

How to pause nodejs flowing stream when destination is full

$ node --version
v0.10.29

类似于"Cannot switch to old mode now" - Node.JS apn module error in tls.connect function I'm getting a "Cannot switch to old mode now" error thrown when pausing a readable stream (in this case a HTTP response/IncomingMessage)

_stream_readable.js:732
    throw new Error('Cannot switch to old mode now.');
          ^
Error: Cannot switch to old mode now.
    at emitDataEvents (_stream_readable.js:732:11)
    at IncomingMessage.Readable.pause (_stream_readable.js:723:3)

IncomingMessage 正文中有 XML,我正在将其传送到 readable.pause()readable.resume() 上的 sax-js handler. The handler then writes output to a PassThrough stream which is piped to some destination. Reading the docs 我不确定我在说什么做错了。是否有关于流动流的内容我遗漏了,或者我在下面实施了错误的模式?

function wrapStream(incoming) {
  var dest = new PassThrough();
  dest.setEncoding("utf8");

  dest.on("drain", function () {
    incoming.resume();
  });

  var saxStream = sax.createStream(true, {});

  saxStream.print = function() {
    var args = Array.prototype.slice.apply(arguments);

    /*
     * It's my understanding that if the dest stream is full,
     * we should pause the IncomingMessage
     * until the dest drains.
     */
    if (!dest.write.apply(dest, args)) {
      // throws error here.
      incoming.pause();
    }
  };

  /*
   * Attach handlers to saxStream here.
   * They use the print() function to write data to dest.
   */

  saxStream.on("end", function() {
    dest.end();
  });

  incoming.pipe(saxStream);

  return dest;
}

var output = fs.createWriteStream("/tmp/test.xml");

http.get(url, function(res) {
  var saxStream = wrapStream(res);

  saxStream.pipe(output);
});

Streams 嵌入了一种名为背压的机制。当目标流繁忙时,自动将一个流通过管道传输到另一个流。除非您使用旧流(节点 0.8),但我认为情况并非如此。

你应该只做 req.pipe(saxStream).