DEV Community

Cover image for Parsing Node Command-Line Arguments
Kayode
Kayode

Posted on • Originally published at blog.zt4ff.dev

Parsing Node Command-Line Arguments

Node provides an option to pass in command-line arguments when running a node application. For instance, you can pass in a flag to npm to install a package as a dependency or dev-dependency:

node install -D <package-name> 
Enter fullscreen mode Exit fullscreen mode

The arguments passed are accessible from the process.argv property in your node application as an array of strings where the first element is the process.execPath while the second element is the path to the file being executed.

// app.js
const arg = process.argv
console.log(arg)

// Output - running `node app.js kayode`
// [
//   '/home/gitpod/.nvm/versions/node/v16.11.0/bin/node',
//   '/workspace/node_test/app.js',
//   '44'
// ]
Enter fullscreen mode Exit fullscreen mode

Yargs is a node package for parsing CLI arguments. To install the package in your application run in your terminal:

npm install -S yargs

Let's write some codes then I'll explain what the code is:

// app.js
const yargs = require('yargs');

const arg = yargs(process.argv.slice(2)).argv;
console.log(arg);

// Output running - node app.js run -o fast
// { _: [ 'run' ], o: 'fast', '$0': 'test.js' }
Enter fullscreen mode Exit fullscreen mode

We won't mostly make use of the first two elements from the process.argv so we'd slice the array from the third position.

Yargs provides a an helper function to do this:

const yargs = require('yargs');
const { hideBin } = require('yargs/helpers');

const arg = yargs(hideBin(process.argv)).argv
Enter fullscreen mode Exit fullscreen mode

The object returned by the function usually contains these three major property:

  • non-hyphenated options accessible via arg._ as an array
  • hyphenated options accessible via the flag name e.g arg.o
  • arg.$0 the name of the node application file

A simple example

Next we'd build an application that takes a fullname(f) and lastname(l) option and prints a welcome message

// app.js
const yargs = require('yargs');
const { hideBin } = require('yargs/helpers');

const { firstname, lastname } = yargs(hideBin(process.env))
    .option('f', {
        alias: 'firstname', // -f or --filename
        description: 'your firstname',
        type: 'string'
    })
    .option('l', { // chaining another option
        alias: 'lastname', // -l or --lastname
        description: 'your lastname',
        type: 'string'
    }).argv

console.log(`Hello, welcome ${firstname} ${lastname}`)

// Output running - node app.js -f John -l Doe
// Hello, welcome John Doe
Enter fullscreen mode Exit fullscreen mode

More example

// app.js
const yargs = require("yargs");
const { hideBin } = require("yargs/helpers");

const arg = yargs(hideBin(process.argv))
  .usage("Usage: $0 -f string -l string")
  .option("f", {
    alias: "firstname",
    type: "string",
    description: "your firstname",
  })
  .option("l", {
    alias: "lastname",
    type: "string",
    description: "yout last name",
  })
    .help("h")
  .demandOption("f")
  .default("l", "Default").argv;

console.log(`Welcome, ${arg.firstname} ${arg.lastname}`);
Enter fullscreen mode Exit fullscreen mode

Running node app.js -h will out a CLI showing the help and descriptions of the arguments:
command-line output

Discussion (0)