Search This Blog

2021/06/01

Using child_process to run long running task

long.js

//child
const longTask = () => {
let sum = 0;
for (let i = 0; i < 1e9; i++) {
sum += i;
};
return sum;
};

process.on('message', (msg) => {
console.log("child",msg);
const sum = longTask();
process.send(sum);
});



We have long running task longTask as above.To call this long running task we
create end point as below

Main.js

//parent

const http = require('http');
const { fork } = require('child_process');
const server = http.createServer();


server.on('request', (req, res) => {
if (req.url === '/get') {
const compute = fork('long.js');
compute.send('start');
compute.on('message', sum => {
res.end(`Sum is ${sum}`);
});
} else {
res.end('Ok')
}
});
server.listen(3000);


when localhost:3000/get called long.js is forked and now when message from
child process come response is send.