[英]Node.js - callback outside a callback?
I'm quite new to Node.js, so please bear with me... 我对Node.js还是很陌生,所以请多多包涵...
Bascially, I have a proxy server, and I want to intercept HTTP body packets. 基本上,我有一个代理服务器,并且想拦截HTTP主体数据包。 These packets are fired off through zeromq to another process outside of Node.js (a C program) and the response (the modified packet), must be written back out as the response from the proxy.
这些数据包通过zeromq触发到Node.js(C程序)之外的另一个进程,并且响应(修改后的数据包)必须作为代理的响应写回。 I hope I'm making sense.
我希望我有道理。
I've commented the code with the bits I'm stuck with 我已经用固定的位注释了代码
Here is my javascript code: 这是我的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);
I hope someone can help... 我希望有人能帮帮忙...
as Pointy alread has pointed out (i see what you did there ;) ), you need to make requester.send(chunk);
正如Pointy所指出的(我看到您在那做的事情了)),您需要进行
requester.send(chunk);
asynchronous by adding a callback, which gets invoked as soon as your C Program is finished doing what it does. 通过添加回调来实现异步,该回调在C程序完成其操作后立即被调用。 You also could do it non-async ( -> synchronous) by directly returning the value.
您也可以通过直接返回值来实现非异步(->同步)。
I'd dig in some tutorials about "how to make your own node.js module with bindings"; 我会在“如何使用绑定创建自己的node.js模块”的一些教程中进行深入研究;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.