'NodeJS, multiple express server processes serving on single port (a la cluster mode) but connected with alternative IPC setup
The following code is a popular use of Node's cluster module:
import cluster from 'cluster';
import http from 'http';
import { cpus } from 'os';
import process from 'process';
const numCPUs = cpus().length;
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
When I first saw this it made no sense why this was possible, until I did some reading and found that 'listen' does something different behind-the-scenes if it detects itself to be a cluster fork or master.
As I understand it, the only true listener to port 8000 is the master process, the forked processes communicate with the master process via an IPC socket.
I want to do something similar, but without using the cluster module.
I want to setup an http server as an independent process using port 8000, while also running one or more processes (not forks) with http servers 'listening' to port 8000 using the behind-the-scenes IPC as described above.
How is this done without using the cluster module?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
