如何使用请求使用转换流? [英] How to use transform stream using request?

查看:41
本文介绍了如何使用请求使用转换流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically, I would like to alter the http response before sending it to the client, using transform streams, but my code below throws an error : [Error: write after end].

关于http://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback 说:

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

Calling write() after calling end() will raise an error.

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

How can I prevent write() to be called after end() in this case ?

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);

推荐答案

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

A stream is supposed to be used only once, but you're using the same transform stream for each incoming request. On the first request it will work, but when x closes, so will parser: that's why on the second client request you'll see the write after end error.

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

To fix this, just create a new transform stream on each use:

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);

这篇关于如何使用请求使用转换流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆