diff --git a/bin/index.js b/bin/index.js new file mode 100755 index 00000000..f62e9c02 --- /dev/null +++ b/bin/index.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +const path = require('path'); +const fs = require('fs'); + +const jsonata = require('../src/jsonata'); + +/** + * cli usage: + * jsonata + * cat my-file.json | jsonata + * @returns {{expression: string, object: {}}} + */ +function parseArgs() { + const args = process.argv.slice(2); + + if (args.length === 2) { // file and expression given + const [jsonFile, expression] = args; + + let object; + try { + object = require(path.resolve(jsonFile)); + } catch (error) { + // eslint-disable-next-line no-console + console.error(`failed to load json file ${jsonFile}`, error); + process.exit(1); + } + + return { object, expression }; + } else if (args.length === 1) { // expression given, read file contents from stdin + const fileData = fs.readFileSync(0).toString(); + + let object; + try { + object = JSON.parse(fileData); + } catch (error) { + // eslint-disable-next-line no-console + console.error(`failed to load json string from stdin`, error); + process.exit(2); + } + + return { object, expression: args[0] }; + } else { + // eslint-disable-next-line no-console + console.error('invalid number of arguments', process.argv); + process.exit(3); + } +} + +const { expression, object } = parseArgs(); +const result = jsonata(expression).evaluate(object); +// eslint-disable-next-line no-console +console.log(JSON.stringify(result, null, 2)); diff --git a/jsdoc.json b/jsdoc.json index 748152de..9a2d220e 100644 --- a/jsdoc.json +++ b/jsdoc.json @@ -5,7 +5,7 @@ }, "source": { "includePattern": ".+\\.js(doc)?$", - "excludePattern": "(^|\\/|\\\\)_|node_modules|doc|coverage" + "excludePattern": "(^|\\/|\\\\)_|node_modules|doc|coverage|bin" }, "plugins": [], "templates": { diff --git a/package.json b/package.json index c72ab13f..5a39d7c1 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,9 @@ "type": "git", "url": "https://github.com/jsonata-js/jsonata.git" }, + "bin": { + "jsonata": "bin/index.js" + }, "scripts": { "pretest": "npm run lint", "mocha": "node ./node_modules/istanbul/lib/cli.js cover --report cobertura --report html ./node_modules/mocha/bin/_mocha -- \"test/**/*.js\"",