I have a task that requires a lot of computing without IO while executing and I don\'t want to block thread while executing this task. How can I do this in Node.js
The usual way to remove compute intensive stuff from blocking the main thread in node.js is to pass that work off to another process. There are many ways to structure that.
And, these techniques can be combined and one in combination too.
In the first case, you are just creating more processes all doing the same thing.
In the other two cases, you are specifically moving the compute intensive work to child processes so the main process is not burdened or blocked by that work.
There are a number of libraries that help provide an interface for using child processes. One such library provides the webWorker type of interface.
You need background workers and some kind of communication protocol between your web instance and worker instances. For example you can use kue to create tasks queue
// web worker
var kue = require('kue');
var queue = kue.createQueue();
....
app.post('/calculateSomeCrazyStuff', (req, res, err) => {
queue.create('myLongRunningJobName1', {
fibonacciSequence: 52
}).save((err) => {
if (err) {
return next(err);
}
res.status(204).send();
});
});
// jobs worker
var kue = require('kue');
var queue = kue.createQueue();
queue.process('myLongRunningJobName1', function(job, done) {
// calculate fibonacci
done();
});