[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 = ;
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的更多相关文章
- 极简 Node.js 入门 - 2.3 process
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- node.js在windows下的学习笔记(8)---进程管理Process
process是一个全局内置对象,可以在代码中的任何位置访问此对象,这个对象代表我们的node.js代码宿主的操作系统进程对象. 使用process对象可以截获进程的异常.退出等事件,也可以获取进程的 ...
- 关于Node.js的__dirname,__filename,process.cwd(),./文件路径的一些坑
探索 计算机不会欺骗人,一切按照规则执行,说找不到这个文件,那肯定就是真的找不到,至于为什么找不到,那就是因为我们理解有偏差,我最初理解的'./'是当前执行js文件所在的文件夹的绝对路径,然后Node ...
- 系列3|走进Node.js之多进程模型
文:正龙(沪江网校Web前端工程师) 本文原创,转载请注明作者及出处 之前的文章"走进Node.js之HTTP实现分析"中,大家已经了解 Node.js 是如何处理 HTTP 请求 ...
- 避免uncaughtException错误引起node.js进程崩溃
uncaughtException 未捕获的异常, 当node.js 遇到这个错误,整个进程直接崩溃. 或许这俩个人上辈子一定是一对冤家. 或许这俩个人经历了前世500次的回眸才换来了今生的相遇,只可 ...
- 【学习笔记】node.js重构路由功能
摘要:利用node.js模块化实现路由功能,将请求路径作为参数传递给一个route函数,这个函数会根据参数调用一个方法,最后输出浏览器响应内容 1.介绍 node.js是一个基于Chrome V8引擎 ...
- Node.js NPM Tutorial
Node.js NPM Tutorial – How to Get Started with NPM? NPM is the core of any application that is devel ...
- node.js & read argv
node.js & read argv https://nodejs.org/docs/latest/api/process.html https://flaviocopes.com/node ...
- node.js中process进程的概念和child_process子进程模块的使用
进程,你可以把它理解成一个正在运行的程序.node.js中每个应用程序都是进程类的实例对象. node.js中有一个 process 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...
随机推荐
- [BZOJ5317][JSOI2018]部落战争(闵可夫斯基和)
对于点集$A$,$B$,闵可夫斯基和$C=\{(x1+x2,y1+y2)|(x1,x2)\in A,(y1,y2)\in B\}$.由此可知,对于两个凸包$A$,$B$的闵可夫斯基和$C$满足,$C$ ...
- vijos p1768 数学
链接:点我 预处理:b[i][j]表示a[1] ... a[j]中比a[i]小的数的数量. 设 int get_lower_count(int b[], int l, int r) { return ...
- 洛谷P3119 USACO15JAN 草鉴定
题目描述 In an effort to better manage the grazing patterns of his cows, Farmer John has installed one-w ...
- HDU step by step
section 1 不解释~ section 2 1.2.1 a+b coming #include<stdio.h> long long z,x,y; int main( ) { whi ...
- MFC小程序------01 代码管理器
1.代码入库: 2.代码查找: 3.查看全部代码: 4.程序设置: 自己学习MFC写的一个小程序,当中还有很多功能还待完好,比方数据库的导入功能还没有写,但导出功能是能够用的,查找算法也不是非常好,还 ...
- hint.css使用说明
GitHub:http://liu12fei08fei.github.io/html/1hint.html hint.css使用说明 用途 快速实现tooltips提示样式 相关资源 官方网站GitH ...
- MVC批量添加,增加一条记录的同时添加N条集合属性所对应的个体
类别中包含一个产品的集合属性,如何向数据库添加一条类别记录的同时,添加任意多个产品. public class Product { [DisplayName("产品名称")] pu ...
- MVC中使用CKEditor01-基础
本篇体验在MVC中使用CKEditor,仅仅算思路.基础,暂没有把验证等与CKEditor结合在一起考虑. □ 1 使用NUGET引入CKEditorPM> Install-Package CK ...
- andriod获得应用程序的Context
getApplicationContext() getResources().getString(R.string.app_name) //获得程序名称
- Cocos2dx 小技巧(十四)ScrollView实现缩放效果
这阶段心绪比較乱,所以这篇开头就不扯淡了.(谁说大姨夫来了我跟谁急!~~)说到大姨夫我突然想到英雄联盟有个美女讲解叫伊芙蕾亚,她的堂弟ID居然叫:姨夫累呀,好笑吧(呵呵,有点冷~~额,我都说不扯淡了) ...