[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 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...
随机推荐
- hashmap的遍历方法
How to iterate over the entries of a Map? What is the order of iteration - if you are just using Map ...
- VC 操作 EXCEL---插入工作表(Insert.Sheet)方法
看到的资料 http://bbs.csdn.net/topics/198565 自己总结一下 //插入到nIndex工作表之前 void InsertSheet(int nIndex) { sheet ...
- Codeforces Round #359 (Div. 1) A. Robbers' watch 暴力
A. Robbers' watch 题目连接: http://www.codeforces.com/contest/685/problem/A Description Robbers, who att ...
- opencv+vs2012环境搭建教程
1. 安装OpenCV和VS. 本人电脑安装的是opencv2.4.10和vs2012 2.配置环境变量 以下以win8 64位系统为例: 计算机->属性->高级系统设置->环境变量 ...
- Java_基础知识回顾
1.ByteArrayInputStream. ByteArrayOutputStream String str = "ZHANGSAN"; //System.out.printl ...
- 小米路由通过SSH添加静态路由表之后无法跳转的问题
1.确定系统已经开启了转发功能: /etc/sysctl.conf下的配置项目为net.ipv4.ip_forward = 1 2.关闭防火墙的REJECT,也就是修改/etc/config/fire ...
- 四种DCOM错误的区别,0x80080005 0x800706be 0x80010105 0x
四种DCOM错误的区别Differences between the following DCOM error 0x800800050x800706be0x800101050x800706ba ...
- MVC批量更新,使用jQuery Template
在"MVC批量更新,可验证并解决集合元素不连续控制器接收不完全的问题"中,当点击"添加"按钮的时候,通过部分视图,在界面上添加新行.本篇体验使用jQuery T ...
- MVC文件上传05-使用客户端jQuery-File-Upload插件和服务端Backload组件自定义上传文件夹
在零配置情况下,文件的上传文件夹是根目录下的Files文件夹,如何自定义文件的上传文件夹呢? MVC文件上传相关兄弟篇: MVC文件上传01-使用jquery异步上传并客户端验证类型和大小 MVC文 ...
- 开始Admob广告盈利模式详细教程
例子工程源码下载地址: 下载源代码 当然,我也参考了一些网上的资料,主要有: AdMob:在android应用中嵌入广告的方案 如何在Android ...