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. 01-学前入门.Net两种交换模式

    C/S:客户机(Client)/服务器模式(Server)Winfrom应用程序 B/S:浏览器(Browser)/服务器模式(Server)Internet应用模式

  2. python语法(一)

    Python是一种面向对象.直译式电脑编程语言,也是一种功能强大的通用型语言,已经具有近二十年的发展历史,成熟且稳定.在近几年,大数据,人工智能火起来之后也是水涨船高,被越来越多的人知道,并且越来越多 ...

  3. [BZOJ3507][CQOI2014]通配符匹配(DP+Hash)

    显然f[i][j]表示S匹配到第i个通配符,T匹配到第j个字符,是否可行. 一次一起转移两个通配符之间的所有字符,Hash判断. 稍微有点细节.常数极大卡时过排名倒数,可能是没自然溢出的原因. #in ...

  4. HDU 4641 K-string 后缀自动机 并查集

    http://acm.hdu.edu.cn/showproblem.php?pid=4641 https://blog.csdn.net/asdfgh0308/article/details/4096 ...

  5. python调用matlab

    官网链接: https://ww2.mathworks.cn/help/matlab/matlab_external/call-user-script-and-function-from-python ...

  6. Java NIo 笔记001

    1. Channel Channel接口只提供了两个方法: package java.nio.channels; public interface Channel { public boolean i ...

  7. ASP.NET 构建高性能网站 第1篇

    网站优化需要考虑的方面 在用ASP.NET开发网站的时候,性能是永远需要考虑和关注的问题,性能不仅仅只是程序代码执行时候的速度,而是涉及到方方面面的东西. 就拿ASP.NET的一个请求来讲,从浏览器向 ...

  8. SpringBoot无法启动,Process finished with exit code 0

    1.排查yml和properties文件是否配置错误 2.排查POM引入的包

  9. C# 中的动态创建技术

    [转载]原文出处  http://blog.csdn.net/baiyun789/article/details/6156694 第一部分 WinForm控件在窗体中动态居中创建.删除控件及对其赋值 ...

  10. java zxing实现二维码生成和解析zxing实现二维码生成和解析

    原文:https://www.cnblogs.com/zhangzhen894095789/p/6623041.html zxing实现二维码生成和解析   二维码 zxing   二维码的生成与解析 ...