Last active
May 9, 2019 20:21
-
-
Save heisian/2c773d09f2ab13a16994a06bf5173721 to your computer and use it in GitHub Desktop.
Tiny Watcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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