【问题标题】:Node.js - callback outside a callback?Node.js - 回调外的回调?
【发布时间】:2012-01-29 20:20:55
【问题描述】:

我对 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);

希望有人能帮忙...

【问题讨论】:

  • request.send() 不允许传递回调参数吗?如果是这样,那就是你的做法。
  • 嗯。我不确定你是什么意思。我需要找到文档,看看是否有。
  • 看来 requester.send(chunk,x) 的第二个参数 x 必须是整数(标志)。
  • 嗯,好的。好吧,我不是 Node 专家。这就是为什么我没有冒险回答。但是,我怀疑实际答案将以一种或另一种方式涉及一些异步回调设置。节点(通常)不会“等待”任何东西......

标签: javascript events node.js callback zeromq


【解决方案1】:

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

我会深入研究一些关于“如何使用绑定制作自己的 node.js 模块”的教程;

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

【讨论】:

  • 您好,谢谢您的留言。我的 C 程序没有完成——它必​​须不断地监视通过代理的内容。我在想我可能不得不编写一个 Node.js 模块而不是这样做;(
  • 我会看一些展示 eventEmitter 想法的示例,因为您会希望从 C 程序触发“数据”事件到节点
猜你喜欢
  • 1970-01-01
  • 2014-05-13
  • 2014-11-19
  • 2015-12-09
  • 2012-02-12
  • 1970-01-01
  • 2016-11-26
  • 2010-12-24
  • 2017-01-10
相关资源
最近更新 更多