Unnode.js wraps around the Node Cluster API for process clustering. From the documentation:
A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.
require('unnode').isMaster
require('unnode').isWorker
are simple wrappers for
require('cluster').isMaster
require('cluster').isWorker
Here is a quick boilerplate for an Unnode.js app entrypoint file:
require('dotenv').config({path: `${__dirname}/.env`})
const unnode = require('unnode')
if(unnode.isMaster) {
//
// This code will only run in the master process
//
const unnodeMaster = require('unnode').master
const masterLog = require('unnode').masterLogger
unnodeMaster.init(__dirname).catch(error => {
masterLog.safeError('emerg',
'UnnodeMaster.init() failed', error)
})
} else if(unnode.isWorker) {
//
// This code will only run in the worker process(es)
//
const unnodeWorker = require('unnode').worker
const workerLog = require('unnode').workerLogger
try {
unnodeWorker.setupServer(__dirname)
.catch((error) => {
workerLogger.safeError('emerg',
'UnnodeWorker.setupServer() fail',
error)
})
unnodeWorker.runServer()
} catch (error) {
workerLogger.safeError('error',
'Worker failed to start', error)
process.exit(0)
}
}
For a more comprehensive example, see https://github.com/rnurminen/my-websites/blob/master/server.js
Signal handling and process management
Unnode will automatically restart a worker process if it crashes.
SIGINT and SIGTERM signals will attempt to gracefully terminate all workers, and then the master process will exit.
Sending a SIGUSR2 will gracefully restart all workers processes. This allows you to do code hot-reload on the fly.
Next: Vhosts