problems piping in node.js

Problem

We have the following example in node.js

var http = require('http');
http.createServer(function(request, response) {
    var proxy = http.createClient(8083, '127.0.0.1')
    var proxy_request = proxy.request(request.method, request.url, request.headers);
    proxy_request.on('response', function (proxy_response) {
        proxy_response.pipe(response);
        response.writeHead(proxy_response.statusCode, proxy_response.headers);
    });

    setTimeout(function(){
        request.pipe(proxy_request);
    },3000);
}).listen(8081, '127.0.0.1');

The example listen to a request in 127.0.0.1:8081 and sends it to a dummy server (always return 200 OK status code) in 127.0.0.1:8083.

The problem is in the pipe among the input stream (readable) and output stream (writable) when we have a async module before (in this case the setTimeOut timing). The pipe doesn't work and nothing is sent to dummy server in 8083 port.

Maybe, when we have a async call (in this case the setTimeOut) before the pipe call, the inputstream change to a state "not readable", and after the async call the pipe doesn't send anything.

This is just an example...we test it with more async modules from node.js community with the same result (ldapjs, etc)...

We try to fix it with: - request.readable =true; //before pipe call - request.pipe(proxy_request, {end : false}); with the same result (the pipe doesn't work).

Can anybody help us?

Problem courtesy of: alvaizq

Solution

I believe this works as of 0.8.0. I didn't try in 0.6.11+

Solution courtesy of: Jason Young

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.