[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 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...
随机推荐
- 使用Java创建Excel,并添加内容
使用Java创建Excel,并添加内容 一.依赖的Jar包 jxl.jar,使用jxl操作Excel Jxl是一个开源的Java Excel API项目,通过Jxl,Java可以很方便的操作微软的Ex ...
- 模型构建<1>:模型评估-分类问题
对模型的评估是指对模型泛化能力的评估,主要通过具体的性能度量指标来完成.在对比不同模型的能力时,使用不同的性能度量指标可能会导致不同的评判结果,因此也就意味着,模型的好坏只是相对的,什么样的模型是较好 ...
- Android之安全机制
根据android四大框架来解说安全机制 代码安全 java不同于C/C++,java是解释性语言,存在代码被反编译的隐患: 默认混淆器为proguard,最新版本为4.7: proguard还可用来 ...
- 【洛谷】2602: [ZJOI2010]数字计数【数位DP】
P2602 [ZJOI2010]数字计数 题目描述 给定两个正整数a和b,求在[a,b]中的所有整数中,每个数码(digit)各出现了多少次. 输入输出格式 输入格式: 输入文件中仅包含一行两个整数a ...
- Codeforces Round #254 (Div. 1) D. DZY Loves Strings hash 暴力
D. DZY Loves Strings 题目连接: http://codeforces.com/contest/444/problem/D Description DZY loves strings ...
- Codechef December Challenge 2014 Chef and Apple Trees 水题
Chef and Apple Trees Chef loves to prepare delicious dishes. This time, Chef has decided to prepare ...
- android下前端开发诡异bug记录&解决方法
1.border-radius有bug,围不住background 描述:设置了border-radius后,背景色依然会从圆角里冒出来 解决方法:在设置了border-radius的容器加上back ...
- C++中使用REST操作
REST现在是非常流行的一种接口了,但对于C++这种古董语言来说,用起来并不很方便.无论是json操作还是http交互,用起来都比较麻烦. 如果你需要在c++中使用rest操作时,不妨试一下微软的cp ...
- CHANGE USER WHEN I CONNECT TO TEAM FOUNDATION SERVER
Question: I USE TEAM EXPLORER TO CONECT TO TEAM FOUNDATION SERVER 2010, BUT I DO NOT LOGIN OUT, AND ...
- 使用C#中的out关键字,用世界杯演绎
今年的世界杯好看至极,充满着故事性.戏剧性.无论你平常踢不踢球,也不管你是否懂球,你总能从中获得些许的情感释放.世界杯似乎超越了足球本身,成为世界各地人们的"情感总和",一场场比赛 ...