如何在目标已满时暂停nodejs流

时间:2015-06-13 07:15:45

标签: node.js node.js-stream

$ node --version
v0.10.29

"Cannot switch to old mode now" - Node.JS apn module error in tls.connect function类似,我在暂停可读流时遇到“无法立即切换到旧模式”错误(在本例中为HTTP响应/ 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,我正在使用sax-js处理程序。然后,处理程序将输出写入通过管道传送到某个目的地的PassThrough流。阅读readable.pause()readable.resume()上的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);
});

1 个答案:

答案 0 :(得分:0)

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

您应该req.pipe(saxStream)