Skip to content

Instantly share code, notes, and snippets.

@JuanSierra
Last active July 31, 2023 17:59
Show Gist options
  • Save JuanSierra/bb4604636435e3b3ee8df5ea7dcc6e7f to your computer and use it in GitHub Desktop.
Save JuanSierra/bb4604636435e3b3ee8df5ea7dcc6e7f to your computer and use it in GitHub Desktop.
child_process fork
// compute.js
const longComputation = () => {
let sum = 0;
for (let i = 0; i < 1e9; i++) {
sum += i;
};
return sum;
};
process.on('message', (msg) => {
const sum = longComputation();
process.send(sum);
});
// main.js
const http = require('http');
const { fork } = require('child_process');
const server = http.createServer();
server.on('request', (req, res) => {
if (req.url === '/compute') {
const compute = fork('compute.js');
compute.send('start');
compute.on('message', sum => {
res.end(`Sum is ${sum}`);
});
} else {
res.end('Ok')
}
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment