我很新的Node.js,所以請忍受我...Node.js - 回調之外的回調?
Bascially,我有一個代理服務器,我想攔截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()'允許一個回調參數傳遞?如果是這樣,那你就是這麼做的。 – Pointy 2012-01-29 20:24:08
嗯。我不確定你是什麼意思。我需要找到文檔,看看它是否。 – Eamorr 2012-01-29 20:27:19
看起來第二個參數是x,對於requester.send(chunk,x)必須是一個整數(標誌)。 – Eamorr 2012-01-29 20:37:04