Skip to content

Instantly share code, notes, and snippets.

@speaud
Last active May 13, 2020 01:14
Show Gist options
  • Save speaud/9af9f564b71c86a135daae2d555f2ca6 to your computer and use it in GitHub Desktop.
Save speaud/9af9f564b71c86a135daae2d555f2ca6 to your computer and use it in GitHub Desktop.
A node process to watch file/directory for changes. Native implementation of the "live reload" experience web developers praise.

This is a native implementation of the web developers beloved "live reload," experience for a Node.js program.

This Node process will watch a file or directory (i.e., the program source).

When a change occurs then program will reload without manual intervention.

node watch --runtime index.js

node watch --runtime build/

const process = require('process');
const { fork } = require('child_process');
const { watch, unwatchFile } = require('fs');
const runtimeFlag = '--runtime'
const logr = msg => console.log(`>> WATCH: ${msg}`)
let runtime;
function init() {
if (process.argv.includes(runtimeFlag)) {
const flagIndex = process.argv.indexOf('--runtime')
const flagValue = process.argv[flagIndex + 1]
runtime = flagValue
logr(`Runtime file set to ${runtime}`)
} else {
console.error(`The ${runtimeFlag} and value is required`)
process.exit(1)
}
}
function main() {
let instance = fork(runtime);
logr('Server started');
watch(runtime, (eventType, filename) => {
instance.kill();
instance = fork(runtime);
logr(`Event triggered restart [type=${eventType}] [on=${filename}]`);
});
process.on('SIGINT', () => {
instance.kill();
unwatchFile(runtime);
logr('Server stopped');
process.exit();
});
}
init()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment