contrast
node badcode.js
with
node run.js badcode.js
| 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