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].
Documentation on http://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback says :
Calling write() after calling end() will raise an error.
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);
Transform streams have both readable and writable features. It allows the processing of input data followed by outputting data in the processed format. To create a transform stream, we need to import the Transform class from the Node. js stream module.
A transform stream consists of a pair of streams: a writable stream, known as its writable side, and a readable stream, known as its readable side. Writes to the writable side result in new data being made available for reading from the readable side.
One of the ways of switching the mode of a stream to flowing is to attach a 'data' event listener. A way to switch the readable stream to a flowing mode manually is to call the stream. resume method.
The ReadableStream() constructorThe constructor takes two objects as parameters. The first object is required, and creates a model in JavaScript of the underlying source the data is being read from. The second object is optional, and allows you to specify a custom queuing strategy to use for your stream.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With