Run heavy work in a thread or a child process
Node.js runs your code on one thread, so a long calculation blocks every request. NEWTHREAD(name, data) starts workers/<name>.js in a worker thread and returns a standard Node.js Worker: send it messages with worker.postMessage(value), receive replies with worker.on('message', fn), and stop it with worker.kill(). The second argument (data) is handed to the worker as its starting data. NEWFORK(name) has the same shape but starts a separate child process, which is isolated from the main process (a crash in it does not affect your app).
Inside the worker file, NEWTHREAD() without arguments returns the worker handle: worker.data holds the starting data, worker.message = fn receives messages and worker.postMessage(value) answers. Pass a name prefixed with ~ to use a file by path instead of workers/<name>.js.
require('total5');
const worker = NEWTHREAD();
const start = worker.data.start;
worker.message = function(message) {
let total = start;
for (let i = 1; i <= message.to; i++)
total += i;
worker.postMessage({ total: total });
};exports.install = function() {
ROUTE('GET /sum/{to}/', sum);
};
var thread = NEWTHREAD('sum', { start: 1000 });
function sum($) {
var to = +$.params.to;
var timeout = setTimeout(() => $.invalid('timeout'), 4000);
thread.once('message', function(response) {
clearTimeout(timeout);
$.json(response);
});
thread.postMessage({ to: to });
}