如何使用请求使用转换流?

Jid*_*ide 6 stream request node.js

基本上,我想在使用转换流将http响应发送到客户端之前更改它,但我的代码会抛出错误:[错误:写完后].

http://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback上的文档说:

在调用end()之后调用write()将引发错误.

在这种情况下,如何防止在end()之后调用write()?

var request = require('request');
var Transform = require('stream').Transform;
var http = require('http');

var parser = new Transform();
parser._transform = function(data, encoding, done) {
  console.log(data);
  this.push(data);
  done();
};

parser.on('error', function(error) {
  console.log(error);
});

http.createServer(function (req, resp) {
  var dest = 'http://stackoverflow.com/';
  var x = request({url:dest, encoding:null})

  x.pipe(parser).pipe(resp)
}).listen(8000);
Run Code Online (Sandbox Code Playgroud)

Pau*_*gel 13

流应该只使用一次,但是您为每个传入请求使用相同的转换流.在第一个请求它将工作,但是当x关闭,所以将parser:这就是为什么在第二个客户端请求你会看到write after end错误.

要解决此问题,只需在每次使用时创建一个新的转换流:

function createParser () {
    var parser = new Transform();
    parser._transform = function(data, encoding, done) {
        console.log(data);
        this.push(data);
        done();
    };
    return parser;
}

http.createServer(function (req, resp) {
  var dest = 'http://stackoverflow.com/';
  var x = request({url:dest, encoding:null})

  x.pipe(createParser()).pipe(resp)
}).listen(8000);
Run Code Online (Sandbox Code Playgroud)