Skip to content

Tutorial 04 Parse argv

Sam Cao edited this page Jun 30, 2023 · 7 revisions

Goals

In this tutorial, you are going to learn:

  • How to pass the command-line arguments.
  • How to leverage any Node.js command-line parsing modules.

Steps

  • Usually process.argv carries the command-line arguments in Node.js, however, process.argv only has one argument which is the path of java. Jaspiler exposes jaspiler.argv for the scripts to get the command-line arguments. Please be aware that jaspiler.argv[0] is the script path. The backward compatible way is to update the process.argv.
process.argv = [process.argv[0], ...jaspiler.argv];
  • Once the process.argv is updated, you may leverage any Node.js command-line parsing modules. For example, let's use yargs.
process.argv = [process.argv[0], ...jaspiler.argv];

const yargs = require('yargs');

const argv = yargs
  .option('input', {
    alias: 'i',
    type: 'string',
    describe: 'the input',
    demandOption: true,
  })
  .option('output', {
    alias: 'o',
    type: 'string',
    describe: 'the output',
    demandOption: true,
  })
  .version('1.0.0')
  .help()
  .argv;

console.info();
console.info(` Input: ${argv.input}`);
console.info(`Output: ${argv.output}`);
  • The output is:
$ java -jar Jaspiler-*.jar 04_parse_argv.js -i a -o b

 Input: a
Output: b

$ java -jar Jaspiler-*.jar 04_parse_argv.js --help

Options:
  -i, --input    the input                                   [string] [required]
  -o, --output   the output                                  [string] [required]
      --version  Show version number                                   [boolean]
      --help     Show help                                             [boolean]

Summary

  • Jaspiler allows the scripts to parse the argv in the Node.js way.
  • All kinds of Node.js command-line parsing modules can be used.
  • The script itself is supposed to be the first argument.
Clone this wiki locally