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. UVA1378 A funny stone game

    博弈论. 就是有一堆石子你拿走一堆中的一个,然后再向后面两堆中加两个问胜负 i<j<=k 所以我们可以直接通过sg函数计算,考虑问题的奇偶性,如果这一位是奇的我们才考虑,偶的可以模仿 然后 ...

  2. bzoj 3209 数位DP+欧拉定理

    枚举1的个数,统计有那么多1的数的个数 /************************************************************** Problem: 3209 Us ...

  3. 细说React(二)

    上篇文章主要介绍了React的基本用法,这次将介绍一个React路由组件—react-router. 在 web 应用开发中,路由系统是不可或缺的一部分.在浏览器当前的 URL 发生变化时,路由系统会 ...

  4. jquery中的 $.fn $.fx

    $.fn是指 jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效. 如扩展$.fn.abc() 那么你可以这样子:$("#div").abc(); 常使 ...

  5. 特殊字符\u2028导致的Javascript脚本异常

    这原本是个小错误,但排查花了不少时间,因此写下来和大家分享一下. 起因 通过Ajax动态从后台读取文章内容,并显示在页面上,加载到某篇文章的时候,报javascript语法错误,无法显示文章内容. A ...

  6. spring mvc 下 applicationContext 和webApplicationContext

    spring中的ApplicationContexts可以被限制在不同的作用域.在web框架中,每个DispatcherServlet有它自己的WebApplicationContext,它包含了Di ...

  7. Python之“可变”的tuple

    前面我们看到了tuple一旦创建就不能修改.现在,我们来看一个"可变"的tuple: >>> t = ('a', 'b', ['A', 'B']) 注意到 t 有 ...

  8. andriod 文本居中: android:gravity="center"

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&q ...

  9. 引用jar版本错误

    [INFO] Scanning for projects... [ERROR] The build could not read 1 project -> [Help 1] [ERROR]    ...

  10. 使用POI操作Excel时对事先写入模板的公式强制执行

    场景:POI读取Excel模板. 当使用POI操作Excel时,发现由POI生成的公式能够在打开Excel是被执行, 而事先手工写入Excel模板文件的公式则不自动被调用,必须手动双击该Cell才能生 ...