How to avoid blocking the main thread in node.js?

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

Will do

setTimeout(myCalculationFunc(), 0);

- the best way to keep the server from responding to other requests?

+4
source share
3 answers

I created a simple example using child_process to do a heavy calculation if you want to use it.

You can do it as follows:

 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); 
+4
source

But what if the server request needs to perform calculations that take some time?

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

You need to get back into the event loop and process processes as quickly as possible or use IO for heavy lifting.

The actual node.js server just needs to send messages to all your services, and not run any of these services.

+2
source

Another possibility is to use the WebWorkers module. It is not as simple as something like

background(func, succ, fail)

but not too far.

0
source

All Articles