Skip to content

Instantly share code, notes, and snippets.

@monochromer
Created May 13, 2019 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monochromer/b624e0b4f8b143b7c8244a527ca39e67 to your computer and use it in GitHub Desktop.
Save monochromer/b624e0b4f8b143b7c8244a527ca39e67 to your computer and use it in GitHub Desktop.
Node.js cluster demo
const cluster = require('cluster');
const os = require('os');
const pid = process.pid;
const cpusCount = os.cpus().length;
if (cluster.isMaster) {
console.log(`CPUs: ${cpusCount}`);
console.log(`Master started. Pid: ${pid}`);
for (let i = 0; i < cpusCount - 1; i++) {
const worker = cluster.fork();
}
cluster.on('fork', (worker) => {
// console.log(`Worker #${worker.id} is forked =)`);
});
cluster.on('online', (worker) => {
console.log(`Worker #${worker.id} with pid ${worker.process.pid} is online =)`);
});
cluster.on('listening', (worker, address) => {
// console.log(`The worker #${worker.id} is now connected to ${JSON.stringify(address)}`);
});
cluster.on('disconnect', (worker) => {
console.log(`The worker #${worker.id} has disconnected`);
});
cluster.on('exit', (worker, code) => {
console.log(`Worker died! Pid: ${worker.process.pid}. Code ${code}`);
if (code === 1) {
cluster.fork();
}
});
cluster.on('message', (worker, message, handle) => {});
}
if (cluster.isWorker) {
require('./worker.js');
}
module.exports = (req, res) => {
for (let i = 0; i < 1e7; i++) {}
res.end('end');
}
require('./cluster');
const http = require('http');
const handler = require('./handler');
// const pid = process.pid;
const port = process.env.PORT || 3000;
const server = http
.createServer(handler)
.listen(port, () => {
// console.log(`Worker started. Pid: ${pid}`);
});
// https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_event_uncaughtexception
process.on('uncaughtException', (err) => {
console.error(`${(new Date).toUTCString()} uncaught exception: ${err.message}`);
console.error(err.stack);
process.exit(1);
});
// https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_event_unhandledrejection
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
console.error(`${(new Date).toUTCString()}. ${reason.message}`);
console.error(reason.stack);
process.exit(1);
});
// https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_signal_events
process.on('SIGINT', () => {
console.log('Signal is SIGINT');
server.close(() => {
process.exit(0);
})
});
process.on('SIGTERM', () => {
console.log('Signal is SIGTERM');
server.close(() => {
process.exit(0);
})
});
process.on('SIGUSR2', () => {
console.log('Signal is SIGUSR2');
server.close(() => {
process.exit(1);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment