Skip to content

Instantly share code, notes, and snippets.

@mtorre4580
Created April 9, 2023 18:29
Show Gist options
  • Save mtorre4580/9d79e012d6e8830178b65108568e5712 to your computer and use it in GitHub Desktop.
Save mtorre4580/9d79e012d6e8830178b65108568e5712 to your computer and use it in GitHub Desktop.
Example fork process to handle intesive work load to avoid block the main process in Node.js
/**
* Example to simulate a intesive work, sum the value recieved
* @param {number} value
*/
const handlerHeavyOperation = (value = 0) => {
let res = value;
for (let i = 0; i < 90000; i++) {
res += i;
}
return res;
};
// Listener the message and send the result to the main process
process.on("message", (value) => {
const result = handlerHeavyOperation(value);
process.send(result);
});
const express = require("express");
const { fork } = require("child_process");
const app = express();
const port = process.env.PORT || 3001;
// Endpoint with heavy operation
app.get("/heavy", (req, res) => {
// Retrieve the value from query-params
const { value } = req.query;
// Create a fork process to handle the heavy operation
const process = fork("./heavy_operation");
// Send the value recieved
process.send(value);
// Listener when the operation is finished
process.on("message", (result) => res.json({ result }));
});
app.listen(port, () => {
console.log(`API listen in port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment