Skip to content

Instantly share code, notes, and snippets.

@pineapplemachine
Created July 24, 2018 07:23
Show Gist options
  • Select an option

  • Save pineapplemachine/88abce4d85d8ed7f49362e37076e0be6 to your computer and use it in GitHub Desktop.

Select an option

Save pineapplemachine/88abce4d85d8ed7f49362e37076e0be6 to your computer and use it in GitHub Desktop.
Simple watcher to run a shell command when a file changes
// Watch a file or directory recursively and run a shell
// command any time a change to that path is observed.
// Usage:
// node watch.js <path> <command>
// For example:
// node watch.js style.scss "sass style.scss style.css"
const childProcess = require("child_process");
const fs = require('fs');
const path = process.argv[2];
const command = process.argv[3];
console.log(`Running "${command}" on changes to "${path}".`);
let running = false;
let lastRunTime = 0;
fs.watch(path, {recursive: true}, function(){
const now = (new Date()).getTime();
if(running || (now - lastRunTime) < 250) return;
console.log((new Date()).toISOString() + " > " + command);
running = true;
lastRunTime = now;
const proc = childProcess.exec(command);
proc.stdout.on("data", function(data){
process.stdout.write(data.toString());
});
proc.stderr.on("data", function(data){
process.stderr.write(data.toString());
});
proc.on("exit", function(){
running = false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment