Node Streams: piping a reference to a stream doesn't update the original stream

193 views Asked by At

Updated to better explain problem: I'm trying to build a simple proxy server module which will allow implementers to listen for and modify the response which comes from the origin server. When the proxy receives the response, I am emitting a customResponse message with a reference to the response stream. Anybody listening to that event should be able to pipe onto the response and implement custom business logic. The module should take care of the "final" pipe back to the client - otherwise it wouldn't be a proxy (see example code below).

  1. Installation

    npm install eventemitter3 && npm install event-stream && touch index.js
    
  2. index.js

    var http = require("http");
    var EE3 = require('eventemitter3');
    var es = require("event-stream");
    
    var dispatcher = new EE3();
    dispatcher.on("customResponse", function (response) {
        // Implementers would implement duplex or transform streams here
        // and modify the stream data.
        response.pipe(es.mapSync(function (data) {
            return data.toString().replace("sometext", "othertext");
        }));
    });
    
    http.createServer(function (req, res) {
        // BEGIN MODULE CODE - THIS WILL HAVE AN API AND WILL RETURN
        // THE EVENT EMITTER FOR IMPLEMENTERS TO LISTEN TO
        http.request({
            host: "localhost",
            port: 9000,
            path: "/path/to/a/file.txt"
        }, function (response) {
            // Dispatch the event, allow consumers to pipe onto response
            dispatcher.emit("customResponse", response);
    
            // Here's where the problem is - the "response" stream
            // may have been piped onto, but we don't have a reference
            // to that new stream. If the data was modified by a consumer,
            // we don't see that new data here.
            response.pipe(res);
        }).end();
        // END MODULE CODE
    }).listen(7000);
    
0

There are 0 answers