Heavy computing out of load from the main event loop in Node.js

For some user queries, I need to do some heavy calculations (about 100 ms of time); and, of course, I don’t want to execute them in the loop of the main node event, so that it does not allow serving other requests.

The most obvious, but certainly not the cleanest way to solve this problem is to upload the calculations to another program and wait for the results asynchronously.

Is there a way to do this without leaving the node process (and implementing interprocess communications)? For instance. something like that:

var compute = function (input) { var i, result = input; for (i = 0; i < 1000000; i++) { result = md5(result); } } var controller = function (req, res) { offload(compute, req.params.input, function(result) { res.send(result); }); } 
+4
source share
2 answers

I found the compute-cluster module, which seems to be designed specifically for my purposes. It generates child processes, and communication is done using IPC (no sockets).

+3
source

JavaScript does not support threads, and node.js does not provide them with any interface, so you need to rely on the library to make threads work. See node-fibers and node-threads-a-go-go for possible solutions.

If you are looking for a way to make IPC a little easier with node.js, then consider using the zeromq library ( node.js bindings ). This multi-related answer may be helpful.

+1
source

Source: https://habr.com/ru/post/1412321/


All Articles