Skip to content

Instantly share code, notes, and snippets.

@heisian
Last active May 9, 2019 20:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heisian/2c773d09f2ab13a16994a06bf5173721 to your computer and use it in GitHub Desktop.
Save heisian/2c773d09f2ab13a16994a06bf5173721 to your computer and use it in GitHub Desktop.
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