Spawning Node child processes (using fork())

JS
S
JavaScript

Simple example of spawning a node process to perform additional/expensive computations. Each process has its own memory, with their own V8 instances. * Unix Signals and Pipes are kept to allow Inter-Process Communication (IPC) between the 2 PIDs.

1// ------------------------------------------------------------------------
2// HTTP Server (server.js)
3const http = require('http');
4const { fork } = require('child_process');
5
6const server = http.createServer();
7server.on('request', (req, res) => {
8    if (req.url === '/ai') {
9        const ai = fork('ai.js');
10        ai.send({id: 12121});
11        ai.on('message', result =>{
12            const parsedResult = JSON.stringify(result);
13            res.end(`AI computation generated result: ${parsedResult}`);
14        });
15    } else {
16        res.end('Ok')
17    }
18});
19server.listen(3000);
20
21// ------------------------------------------------------------------------
22// Computation Sample Process (ai.js)
23const EventEmitter = require('events');
24class AIInterface extends EventEmitter {
25  execute() {
26    setTimeout(()=>{
27        this.emit('data',{computation: Math.random().toFixed(2)});
28    },500);
29  }
30}
31
32const aiInterface = new AIInterface();
33process.on('message', (msg) => {
34    aiInterface.on('data',(data) => {
35        process.send(data);
36    });
37    aiInterface.execute();
38});

Created on 7/31/2017