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 = ;
for (let i = ; 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:/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 = ;
for (let i = ; 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()

[Node.js] Child Process with fork() to handle heavy calculation process的更多相关文章

  1. 极简 Node.js 入门 - 2.3 process

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  2. node.js在windows下的学习笔记(8)---进程管理Process

    process是一个全局内置对象,可以在代码中的任何位置访问此对象,这个对象代表我们的node.js代码宿主的操作系统进程对象. 使用process对象可以截获进程的异常.退出等事件,也可以获取进程的 ...

  3. 关于Node.js的__dirname,__filename,process.cwd(),./文件路径的一些坑

    探索 计算机不会欺骗人,一切按照规则执行,说找不到这个文件,那肯定就是真的找不到,至于为什么找不到,那就是因为我们理解有偏差,我最初理解的'./'是当前执行js文件所在的文件夹的绝对路径,然后Node ...

  4. 系列3|走进Node.js之多进程模型

    文:正龙(沪江网校Web前端工程师) 本文原创,转载请注明作者及出处 之前的文章"走进Node.js之HTTP实现分析"中,大家已经了解 Node.js 是如何处理 HTTP 请求 ...

  5. 避免uncaughtException错误引起node.js进程崩溃

    uncaughtException 未捕获的异常, 当node.js 遇到这个错误,整个进程直接崩溃. 或许这俩个人上辈子一定是一对冤家. 或许这俩个人经历了前世500次的回眸才换来了今生的相遇,只可 ...

  6. 【学习笔记】node.js重构路由功能

    摘要:利用node.js模块化实现路由功能,将请求路径作为参数传递给一个route函数,这个函数会根据参数调用一个方法,最后输出浏览器响应内容 1.介绍 node.js是一个基于Chrome V8引擎 ...

  7. Node.js NPM Tutorial

    Node.js NPM Tutorial – How to Get Started with NPM? NPM is the core of any application that is devel ...

  8. node.js & read argv

    node.js & read argv https://nodejs.org/docs/latest/api/process.html https://flaviocopes.com/node ...

  9. node.js中process进程的概念和child_process子进程模块的使用

    进程,你可以把它理解成一个正在运行的程序.node.js中每个应用程序都是进程类的实例对象. node.js中有一个 process 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...

随机推荐

  1. ARC 067 E - Grouping

    题面在这里! 很显然是个暴力dp. 我们先枚举一下 队伍人数的种类,然后再逆序枚举一下dp数组里的总人数(顺序就会算重),最后枚举一下这种队伍的数量,之后就可以O(1)算方案了. 具体的,O(1)算方 ...

  2. 【10.26校内测试】【状压?DP】【最小生成树?搜索?】

    Solution 据说正解DP30行??? 然后写了100行的状压DP?? 疯狂特判,一算极限时间复杂度过不了aaa!! 然而还是过了....QAQ 所以我定的状态是待转移的位置的前三位,用6位二进制 ...

  3. Loj10164 数字游戏1

    题目描述 科协里最近很流行数字游戏.某人命名了一种不降数,这种数字必须满足从左到右各位数字成小于等于的关系,如 123,446.现在大家决定玩一个游戏,指定一个整数闭区间 [a,b][a,b][a,b ...

  4. java编译优化

    #java编译器对`String常量表达式`的优化:  - 1.String+String 可以被编译器识别为常量表达 String a="ab" ; String b=" ...

  5. The YubiKey NEO -- Smartcard features

    Smartcard features on the YubiKey NEO YubiKeys are a line of small and low-cost hardware security to ...

  6. USB PIC Programmer (Brenner8)

    http://uzzors2k.4hv.org/index.php?page=usbpicprog My Tait Serial programmer works alright, but not e ...

  7. C#中的IDisposable模式

    当谈到垃圾回收,在C#中,托管资源的垃圾回收是通过CLR的Garbage Collection来实现的,Garbage Collection会调用堆栈上对象的析构函数完成对象的释放工作:而对于一些非托 ...

  8. [转载] 关于matlab GUI的一点心得

    转载自 落落轻尘 [Fig文件方式,即使用菜单File->New->GUI来设计界面] 首先值得注意的是,在低版本matlab上制作的含GUI的m文件一般不能在高版本的matlab上面运行 ...

  9. 如何更改linux文件目录拥有者及用户组

    查看用户和组   1 首先对于经验操作之前,我们先看下当前系统下的用户和组.whoami 查看当前登陆用户 2 Passwd文件存储当前系统所有用户,而组文件/etc/group记录. 3 一个用户可 ...

  10. [iOS] UIView的clipsTobounds属性

    如题,有两个view: view1,view2view2添加view1到中,如果view2大于view1,或者view2的坐标不全在view1的范围内,view2是盖着view1的,意思就是超出的部份 ...