Skip to content

Instantly share code, notes, and snippets.

@webgio
Last active February 1, 2017 13:44
Show Gist options
  • Save webgio/4443536 to your computer and use it in GitHub Desktop.
Save webgio/4443536 to your computer and use it in GitHub Desktop.
Node.js script to watch a dir to compile Handlebars.js templates. Needs "npm install watch". Usage: node node-watch-for-handlebars.js [template-dir-to-watch] [optional outputdir]
watch = require('watch');
fs = require('fs');
var cmd = require('child_process').spawn('cmd'), myArgs;
console.log('watcher started');
myArgs = process.argv.slice(2);
myDir = myArgs[0];
outDir = myArgs[1] || '';
outDir = stripTrailingSlash(outDir);
watch.createMonitor(myDir, { interval: 150 }, function (monitor) {
monitor.on("created", function (f, stat) {
compile(f);
})
monitor.on("changed", function (f, curr, prev) {
compile(f);
})
monitor.on("removed", function (f, stat) {
console.log('removed ' + f);
})
})
function compile(f) {
var parts = f.split('.');
var suffix = parts[parts.length - 1];
if (suffix === 'html') {
var html = fs.readFile(f, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
var newFile;
if (outDir == '') {
newFile = f.replace(".html", ".js");
}
else {
var newFileName = getFileName(f);
newFile = outDir + '\\' + newFileName.replace(".html", ".js")
}
var line = 'handlebars.cmd ' + f + " -f " + newFile;
console.log(line);
cmd.stdin.write(line + '\n');
cmd.on('exit', function (code) {
console.log('Child process exited with exit code ' + code);
});
});
}
}
function stripTrailingSlash(str) {
if(str.substr(-1) == '/') {
return str.substr(0, str.length - 1);
}
return str;
}
function getFileName(f) {
return f.replace(/^.*[\\\/]/, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment