[Node.js] Child Process with fork() to handle heavy calculation process

When build server, if we have a API endpoint requires some heavy calculation process, it will block the whole world. In this post, we will see how to use 'child_process' fork() to solve the problem;

 

Let's see the blocking code example:

复制代码
const http = require('http');

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

const server = http.createServer();

server.on('request', (req, res) => {
    if (req.url === '/compute') {
        const sum = longComputation();
        return res.end(`Sum is ${sum}`);
    } else {
        res.end('Ok');
    }
})
复制代码

When we request '/compute' API endpoint, because of 'longCompute', it blocks the world, no other request can go thought.

curl localhost:3000/compute

 

Let's see how to fix it:

1. We will create a compute.js to hold the 'longCompute' function and also listen to the 'message' event on the global:

复制代码
// Compute.js
const longComputation = () => {
    let sum = 0;
    for (let i = 0; i < 1e9; i++) {
        sum += i;
    }
    return sum;
}

// listen the mssage event on the global
// then do the computation
process.on('message', (msg) => {
    const sum = longComputation();
    process.send(sum);
})
复制代码

 

2. In server.js, instead of calling 'longCompute' directly, we fork the compute.js;

Send signal to tell the compute file to start doing the job, then we also need to listen to the event come back after computation is done.

// start processing
compute.send('start');
// listen to the message
compute.on('message', sum => {
    res.end(`Sum is ${sum}`);
});

 

Full code for server.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');
        // start processing
        compute.send('start');
        // listen to the message
        compute.on('message', sum => {
            res.end(`Sum is ${sum}`);
        });
    } else {
        res.end('Ok');
    }
});
server.listen(3000)
复制代码

 

posted @   Zhentiw  阅读(304)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-03-08 [HTML5] Accessibility Implementation for complex component
2017-03-08 [React] Recompose: Theme React Components Live with Context
2017-03-08 [Angular] Using directive to create a simple Credit card validator
2017-03-08 [Docker] Container & image (docker run)
2017-03-08 [Django] Building the rest API
2016-03-08 [RxJS] Reactive Programming - New requests from refresh clicks -- merge()
2016-03-08 [RxJS] Starting a Stream with SwitchMap & switchMapTo
点击右上角即可分享
微信分享提示