DEV Community

Cover image for Parsing Node Command-Line Arguments
Kayode
Kayode

Posted on • Originally published at blog.zt4ff.dev

1

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more