Skip to content

Instantly share code, notes, and snippets.

@aquiseb
Last active January 30, 2019 16:49
Show Gist options
  • Select an option

  • Save aquiseb/369cae3aa51416a08703f15c247866e7 to your computer and use it in GitHub Desktop.

Select an option

Save aquiseb/369cae3aa51416a08703f15c247866e7 to your computer and use it in GitHub Desktop.
Nodejs minimal hot reload function
const cluster = require('cluster');
const chokidar = require('chokidar');
function start() {
// do something here
console.log('START >>');
}
function hot(start, files) {
if (typeof files == 'string') files = [files];
if (typeof start !== 'function') return;
if (cluster.isMaster) {
const watcher = chokidar.watch(files);
let worker = cluster.fork();
watcher.on('ready', () => {
watcher.on('all', (event, filename) => {
console.log('[READY] :::');
worker.send({ type: 'hotreload', args: { filename, id: worker.id } });
worker.on('exit', function(deadWorker, code, signal) {
const deadWorker = worker;
console.log('[EXIT] :::');
// Restart the worker
worker = cluster.fork();
// Note the process IDs
var newPID = worker.process.pid;
var oldPID = deadWorker.process.pid;
// Log the event
console.log('worker ' + oldPID + ' died.');
console.log('worker ' + newPID + ' born.');
});
});
});
} else if (cluster.isWorker) {
start();
process.on('message', ({ type, args }) => {
console.log('MESSAGE', type);
process.disconnect();
});
}
}
module.exports = hot;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment