Node.js Process Fork (IPC) Boilerplate

JS
S
JavaScript

This is a boilerplate to implement simple a simple parent-child process fork using native IPC communication with stdout piping between child and parent processes. Supported also by Electron (Node.js)

1// ================================================================================
2// parent
3const path = require('path');
4const fork = require('child_process').fork;
5
6const program = path.resolve('dist/process/child.js');
7console.log('program', program)
8const parameters = [];
9const options = {
10  stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ]
11};
12
13const child = fork(program, parameters, options);
14child.send({msg: 'process-this-stuff'}, (error) => {
15  if(error) {
16    console.log(error);
17  }
18});
19child.on('message', message => {
20  console.log('message from child:', message);
21  child.disconnect();
22});
23
24process.stdout.pipe(child.stdout)
25child.stdout.on('data', (data) => {
26  console.log(`child stdout:\n${data}`);
27});
28
29child.on('exit', (code, signal) => {
30  console.log(`child process exited with code ${code} and signal ${signal}`);
31});
32
33
34// ================================================================================
35// child
36const EventEmitter = require('events');
37class AIInterface extends EventEmitter {
38  execute() {
39    setTimeout(()=>{
40        this.emit('data',{computation: Math.random().toFixed(2)});
41    },1000);
42  }
43}
44
45const aiInterface = new AIInterface();
46process.on('message', (msg) => {
47    console.log('received message from parent', msg)
48    aiInterface.on('data',(data) => {
49        process.send(data);
50        // process.exit(1);
51    });
52    aiInterface.execute();
53});

Created on 1/9/2019