Skip to content

Instantly share code, notes, and snippets.

@DTrejo
Created July 6, 2010 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DTrejo/465766 to your computer and use it in GitHub Desktop.
Save DTrejo/465766 to your computer and use it in GitHub Desktop.
there should be js here but there isn't so this should throw an error.
// Used to run code in a directory and rerun it if any files are changed.
// Only watches .html, .js, .css
var sys = require('sys'),
fs = require('fs'),
spawn = require('child_process').spawn,
child, // child process which runs the actual code
ignoreExtensions = [ '.dirtydb', '.db'];
//watch all files, restart if problem
run();
//watchFiles(parseFolder('.'), run);
function run() {
// kill if running
if (child !== undefined)
child.kill();
// run the server
child = spawn('node', [process.argv[2]]);
// let the child's 'puts' escape.
child.stdout.addListener('data', function(data) {
sys.print(' ' + data);
});
child.stderr.addListener('error', function(error) {
sys.print(' ' + error);
});
sys.puts('Starting: ' + process.argv[2]);
}
/**
* Parses a folder and returns a list of files
*
* @param root {String}
* @return {Array}
*/
function parseFolder(root) {
var fileList = [];
var files = fs.readdirSync(root);
files.forEach( function (file) {
var path = root + "/" + file;
var stat = fs.statSync(path);
// add to list
if (stat !== undefined && !stat.isDirectory()) {
fileList.push(path);
}
// recur if directory
if (stat !== undefined && stat.isDirectory()) {
fileList = fileList.concat(parseFolder(path));
}
});
return fileList;
}
/**
* Adds change listener to the files
*
* @param files {Array}
*/
function watchFiles(files, callback) {
var config = { persistent: true,
interval: 0
};
sys.puts("watched files:");
files.forEach( function (file) {
// don't include certain files
var ext = file.slice(file.lastIndexOf('.'), file.length);
if(ignoreExtensions.indexOf(ext) !== -1) {
sys.puts("ignored "+file);
return;
}
sys.puts(file);
// if one of the files changes
fs.watchFile(file, config, function (curr, prev) {
if ((curr.mtime + "") != (prev.mtime + "")) {
sys.puts(file + " changed");
if (callback !== undefined) {
callback();
}
}
});
});
}

contrast

node badcode.js

with

node run.js badcode.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment