0

更新以更好地解释问题:我正在尝试构建一个简单的代理服务器模块,该模块将允许实现者监听和修改来自源服务器的响应。当代理收到响应时,我会发出customResponse一条引用响应流的消息。任何监听该事件的人都应该能够通过管道获取响应并实现自定义业务逻辑。该模块应该负责返回客户端的“最终”管道 - 否则它将不是代理(参见下面的示例代码)。

  1. 安装

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

0 回答 0