5

When writing a web server application with node.js it is of course very important to never block the main thread. But what if a server request needs to do calculations that will take some time to complete?

Will doing a

setTimeout(myCalculationFunc(), 0);

be the best way of keeping the server responding to other requests?

Fredrik Wallenius
  • 2,872
  • 2
  • 20
  • 15

3 Answers3

4

I created as simple example using child_process to do heavy calculating if you would like to use it.

You can do it like this:

var http = require("http"),
exec = require("child_process").exec;

http.createServer(function(request, response) {
    var endvalue;
    request.on('data',
    function(data) {
        endvalue = data;
    });
    request.on('end',
    function() {
        exec("node calculate.js "+endvalue,
            function (error, stdout, stderr) {
              response.writeHead(200, {"Content-Type": "text/plain"});
              response.write(stdout);
              response.end();
            });
    });
}).listen(8080);

Calculate.js:

var endvalue = process.argv[2];
    for (i=0;i<=endvalue;i=i+1)
    {
        //just keeping it busy
    }
console.log("FINISHED USING ENDVALUE: "+endvalue);
Marcus Granström
  • 17,816
  • 1
  • 22
  • 21
3

But what if a server request needs to do calculations that will take some time to complete?

The whole idea behind node.js is that it does not do any heavy processing. Any heavy processing should be handled by a worker.

You need to get back to the event loop as quickly as possible and spawn processes or use IO to do the heavy lifting.

The actual node.js server just needs to pass messages around to all your services, not do any of those services.

Raynos
  • 166,823
  • 56
  • 351
  • 396
1

Another possibility is to use the WebWorkers module. Its not quite as easy as something like

background(func, succ, fail)

but its not too far off.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236