Created
August 15, 2018 23:03
-
-
Save fstamour/531bdc6a2cc4f77ec6769c10594aa07e to your computer and use it in GitHub Desktop.
Poor man's nodemon
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
const spawn = require('child_process').spawn; | |
const fs = require('fs'); | |
function debounce(func, wait, immediate) { | |
var timeout; | |
return function() { | |
var context = this, args = arguments; | |
var later = function() { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
function fileChanged(_, filename) { | |
process.stdout.write('\033[2J'); // CLEAR | |
console.log(`main.js changed, reloading...`) | |
var child = spawn('node', [filename]); | |
child.stdin.pipe(process.stdin); | |
child.stdout.pipe(process.stdout); | |
child.on('close', (code) => { | |
console.log(`child process exited with code ${code}`); | |
}); | |
child.unref() | |
} | |
function runOnceThenWatch(filename) { | |
fileChanged(null, filename) | |
fs.watch(filename, debounce(fileChanged, 100)); | |
} | |
runOnceThenWatch('main.js') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment