更新以更好地解释问题:我正在尝试构建一个简单的代理服务器模块,该模块将允许实施者监听和修改来自源服务器的响应。当代理收到响应时,我发出一条customResponse
消息,其中包含对响应流的引用。任何收听该事件的人都应该能够管理响应并实现自定义业务逻辑。该模块应该将" final" 管道返回给客户端 - 否则它不会成为代理(请参阅下面的示例代码)。
npm install eventemitter3 && npm install event-stream && touch 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);