I would like to highlight a server task with high CPU consumption from the user:
./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++) {
When you ask for "localhost: 3000 / resources / test / async", I expect that the rendering of the browser "Hello world, it needs to be sent right away" is very fast and node.js to continue processing and after a while the message "completed" appears in the console "
Instead, the browser continues to wait until node.js completes a large task and then displays the contents. I tried with res.set({ 'Connection': 'close' }); , as well as res.end(); but nothing works as expected. I also did not look googled.
How should I immediately send a response to the client, and the server should continue the tasks?
EDIT
published fork method in solution
source share