Skip to content

Instantly share code, notes, and snippets.

@hidinginabunker
Created April 16, 2011 17:18
Show Gist options
  • Save hidinginabunker/923308 to your computer and use it in GitHub Desktop.
Save hidinginabunker/923308 to your computer and use it in GitHub Desktop.
Command line tool to render a mustache template with a json context file
#!/usr/bin/env node
var
mu = require('Mu'),
fs = require('fs');
var
usage = ''
+ '\n'
+ ' Usage: mustache.js [context] [template]\n'
+ '\n'
+ ' Arguments:\n'
+ ' context context file in json format\n'
+ ' template template file\n'
;
// verify arguments exist before continuing
if(!process.argv[2] || !process.argv[3]) {
console.log(usage);
process.exit(0);
}
var
contextFileName = process.argv[2],
templateFileName = process.argv[3],
context = {};
template = "",
partials = {},
compiled = {};
// read the template context from a json file
fs.readFile(contextFileName, 'ascii', function(err, buffer) {
if(err) {
console.error("Error reading from context file: "+contextFileName);
console.error(err.stack);
process.exit(1);
}
context = JSON.parse(buffer);
// read the mustache template from a file
fs.readFile(templateFileName, 'ascii', function(err, buffer) {
if(err) {
console.error("Error reading from template file: "+templateFileName);
console.error(err.stack);
process.exit(1);
}
template = buffer;
// compile the template
compiled = mu.compileText(template, partials);
// write the rendered template to stdout
compiled(context).addListener('data', function( results ) {
process.stdout.write(results);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment