NodeJS数据吞吐量

我build立了一个可以被客户端访问的NodeJS服务器。 每过一段时间,都需要让服务器连接到另一台服务器,并将检索到的信息反馈给客户端。

连接到第二台服务器是很容易的部分,但说实话,我不知道如何将其发送回客户端。 res.write似乎在与第二台服务器连接时被禁止。

来自客户端的连接由handleGetRequest处理。 与第二个服务器的连接从http.get开始。

 var http = require('http'); var url = require('url'); var server = http.createServer(function(req, res) { var url_parsed = url.parse(req.url, true); if (req.method ==='GET') { handleGetRequest(res, url_parsed); } else { res.end('Method not supported'); } }); handleGetRequest = function(res, url_parsed) { if (url_parsed.path == '/secondary') { var OPTIONS = { hostname: "localhost", port: "8900", path: "/from_primary" } http.get(OPTIONS, function(secget) { resget.on('data', function(chunk) { // either store 'chunk' for later use or send directly }); }).on('error', function(e) { console.log("Error " + e.message); }); } else { res.writeHead(404); } res.end('Closed'); }; server.listen(8000); 

如何将http.requestchunk发送给客户端?

我认为传递callback handleGetRequest将解决这个问题:

 if (req.method === 'GET') { handleGetRequest(url_parsed, function (err, response) { if (err) { return res.sendStatus(500); } res.json(response); }); } else { res.end('Method not supported'); } handleGetRequest = function (url_parsed, callback) { // OPTIONS ... http.get(OPTIONS, function(resget) { var data = ''; resget.on('data', function(chunk) { data += chunk; }); resget.on('end', function() { callback(null, data); }); }).on('error', function(e) { callback(e); }); } 

感谢@TalgatMedetbekov的build议。 我设法实现它是这样的:

 var http = require('http'); var url = require('url'); var server = http.createServer(function(req, res) { var url_parsed = url.parse(req.url, true); if (req.method ==='GET') { handleGetRequest(res, url_parsed); } else { res.end('Method not supported'); } }); handleGetSecondaryRequest = function(callback, res) { var OPTIONS = { hostname: "localhost", port: "8900", path: "/from_primary" } var data = null; http.get(OPTIONS, function(func, data) { func.on('data', function(chunk) { data += chunk; }); func.on('end', function() { callback(res, data); }); }).on('error', function(e) { callback(res, e); }) }; var secReqCallback = function(res, recData) { res.write(recData); res.end("END"); }; handleGetRequest = function(res, url_parsed) { if (url_parsed.path == '/secondary') { handleGetSecondaryRequest(secReqCallback, res); } else { res.writeHead(404); } }; server.listen(8000); 

它的工作,种。 在string前面有一个'undefined',我找不到原因,但是基本的function是完美的。

callback结构对于同步NodeJS的asynchronous性是非常必要的。