0

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);
    
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • possible duplicate of [Node.js Piping the same stream into multiple (writable) targets](http://stackoverflow.com/questions/19553837/node-js-piping-the-same-stream-into-multiple-writable-targets) – laggingreflex Jun 18 '15 at 00:26
  • I updated the question to more clearly explain. I understand pipe chaining and other things addressed by that answer. My situation is different. I am trying to "expose" a stream to the outside world, allow consumers to pipe onto it, and then perform the final *crucial* pipe internally. How can I do this? – Ryan Wheale Jun 23 '15 at 19:57

0 Answers0