我想将服务器高消耗 CPU 任务与用户体验分开:
./main.js:
var express = require('express');
var Test = require('./resources/test');
var http = require('http');
var main = express();
main.set('port', process.env.PORT || 3000);
main.set('views', __dirname + '/views');
main.use(express.logger('dev'));
main.use(express.bodyParser());
main.use(main.router);
main.get('/resources/test/async', Test.testAsync);
main.configure('development', function() {
main.use(express.errorHandler());
});
http.createServer(main).listen(main.get('port'), function(){
console.log('Express server app listening on port ' + main.get('port'));
});
./resources/test.js:
function Test() {}
module.exports = Test;
Test.testAsync = function(req, res) {
res.send(200, "Hello world, this should be sent inmediately");
process.nextTick(function() {
console.log("Simulating large task");
for (var j = 0; j < 1000000000; j++) {
// Simulate large loop
}
console.log("phhhew!! Finished!");
});
};
当请求“localhost:3000/resources/test/async”时,我希望浏览器呈现“Hello world,这应该立即发送”非常快并且 node.js 继续处理,一段时间后在控制台中出现“完成”消息。
相反,浏览器会一直等待,直到 node.js 完成大型任务,然后呈现内容。我试过 res.set({ 'Connection': 'close' }); 和 res.end(); 但没有按预期工作。我也用谷歌搜索没有运气。
如何立即将响应发送给客户端并让服务器继续执行任务?
编辑
在解决方案中发布fork方法
最佳答案
尝试等待而不是占用 CPU:
res.send("Hello world, this should be sent inmediately");
console.log("Response sent.");
setTimeout(function() {
console.log("After-response code running!");
}, 3000);
node.js 是单线程的。如果你用一个繁忙的循环锁定 CPU,整个事情就会停止,直到它完成。
关于javascript - Node.js/ express : respond immediately to client request and continue tasks in nextTick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21288452/