diff --git a/bin/mustache b/bin/mustache index 367fab555..a88c9b4f9 100755 --- a/bin/mustache +++ b/bin/mustache @@ -46,10 +46,23 @@ function readView(cb) { var view = isStdin(viewArg) ? process.openStdin() : fs.createReadStream(viewArg); streamToStr(view, function(str) { - cb(JSON.parse(str)); + cb(parseView(str)); }); } +function parseView(str) { + try { + return JSON.parse(str); + } catch (ex) { + console.error( + 'Shooot, could not parse view as JSON.\n'+ + 'Tips: functions are not valid JSON and keys / values must be surround with double quotes.\n\n'+ + ex.stack); + + process.exit(1); + } +} + function readTemplate(cb) { var template = fs.createReadStream(templateArg); streamToStr(template, cb); diff --git a/test/cli-test.js b/test/cli-test.js index 4db29f458..52cd7deeb 100644 --- a/test/cli-test.js +++ b/test/cli-test.js @@ -28,6 +28,13 @@ describe('Mustache CLI', function () { }); }); + it('writes hints about JSON parsing errors when given invalid JSON', function(done) { + exec('echo {name:"lebron"} | bin/mustache - test/_files/cli.mustache', function(err, stdout, stderr) { + assert.notEqual(stderr.indexOf('Shooot, could not parse view as JSON'), -1); + done(); + }); + }); + it('writes module version into stdout when runned with --version', function(done){ exec('bin/mustache --version', function(err, stdout, stderr) { assert.notEqual(stdout.indexOf(moduleVersion), -1);