Skip to content

Instantly share code, notes, and snippets.

@heisian
Last active May 9, 2019
Embed
What would you like to do?
Tiny Watcher
/**
* Uses fs.watchFile and cluster to watch, fork, and "restart"
* the file that this code is included in. Run this code before
* anything else in the script and it will restart a persistent-
* running fork of itself when the source is modified.
*/
const fs = require('fs')
const cluster = require('cluster')
if (cluster.isMaster) {
const workerFactory = () => cluster.fork()
console.log('Forking child process of self...')
let forked = workerFactory()
fs.watchFile(module.filename, { interval: 150 }, (curr, prev) => {
if (curr.mtime !== prev.mtime) {
console.log('Killing child process of self and restarting...')
forked.kill()
forked = workerFactory()
}
})
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment