Node.js - 回调之外的回调?

时间:2012-01-29 20:20:56

标签: javascript events node.js callback zeromq

我对Node.js很新,所以请耐心等待......

基本上,我有一个代理服务器,我想拦截HTTP正文包。这些数据包通过zeromq发送到Node.js(C程序)之外的另一个进程,并且响应(修改后的数据包)必须作为来自代理的响应写回。我希望我有意义。

我已经用我坚持的位来评论代码

这是我的javascript代码:

var http = require('http');
var util=require('util');
var net=require('net');
var context = require('zmq');

// socket to talk to server
util.puts("Connecting to server...");
var requester=context.createSocket('req');

requester.on("message",function(reply) {
        util.puts("Received reply"+reply.toString());

        //response.write(reply,'binary');   //how do I pick up the `response` variable inside the proxy callback and write with it?!
})

requester.connect("ipc://myfd.ipc")

process.on('SIGINT', function() {
        requester.close()
})




http.createServer(function(request, response) {
        var proxy=http.createClient(80,request.headers['host']);
        var proxy_request=proxy.request(request.method,request.url,request.headers);

        proxy_request.addListener('response',function (proxy_response){
                proxy_response.addListener('data',function(chunk){
                        //util.puts(chunk);

                        requester.send(chunk);   //ok, my C program can read chunks

                        response.write(chunk,'binary');   //I don't want to do this - I want to write the response of `requester.send(chunk)`
               });
                proxy_response.addListener('end',function(){
                        //util.puts("end");
                        response.end();
                });
                response.writeHead(proxy_response.statusCode,proxy_response.headers);
        });


        request.addListener('close',function(){
                //util.puts("close");
        });
        request.addListener('data',function(chunk){
                //util.puts("data");
                proxy_request.write(chunk,'binary');
        });
        request.addListener('end',function(){
                //util.puts("end");
                proxy_request.end();
        });
}).listen(8080);

我希望有人能帮忙......

1 个答案:

答案 0 :(得分:1)

正如Pointy alread指出的那样(我看到你在那里做了什么;)),你需要通过添加一个回调来使requester.send(chunk);异步,一旦你的C程序完成了它的作用就会被调用。您也可以通过直接返回值来进行非异步( - >同步)。

我会在一些教程中深入探讨“如何使用绑定创建自己的node.js模块”;

  1. Good Overview
  2. Simple Async Module by Isaac Schleuters himself