Last active
July 31, 2023 17:59
-
-
Save JuanSierra/bb4604636435e3b3ee8df5ea7dcc6e7f to your computer and use it in GitHub Desktop.
child_process fork
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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