Thursday, February 14, 2019

Creating a CLI For a Node.js Script

Introduction

I've been noodling around with allowing my Node.js script accept arguments and decided it was time to document some of the basics of using a library to give my scripts the flexibility of a CLI flags.

The npm package commander allows any Node.js script to accept flags (unordered arguments) and display usage information or warnings. This tutorial will walk you through the basics of setting up a CLI, confirm that a required flag was submitted, and display any errors with the CLI arguments.

Requirements

You should be fairly comfortable with JavaScript in general and have some working knowledge of how Node.js and command line interfaces works prior to digging into this tutorial.

Required npm packages

In this tutorial, we'll need to ensure the following packages have been install in your project directory:
Note: This tutorial was written with Node.js (version 10.11.0).

Setting Up a Node.js Script With a CLI

Let's start out by requiring the commander module:

const program = require('commander');

Set the flags

Next, we need to set up what options our CLI will have. In this case, we'll set the usage info and foo and bar flags making the foo flag required. The version method can be any number you wish and is entirely optional but it's nice to let your users know how many iterations this script has, right? The usage method tells the users how to use this script as a CLI.

program
  .version('0.0.1')
  .usage('-f <foo> -b <bar>')
  .option('-f, --foo', '*Required* foo')
  .option('-b, --bar', 'bar')
  .parse(process.argv);

Getting the arguments

With the flags set up, the script needs to be able to get at the arguments. We'll use the arguments object to hold those values entered by the user in the terminal. The program object has a nested object called rawArgs that we can iterate through looking for matches to the flags we want to associate with the process argument input. It should be noted that rawArgs escape some special characters like single and double quotes, exclamation points, dollar signs, and so on.

var arguments = {};

for (var i = 0; i < program.rawArgs.length; i++) {
  if (program.rawArgs[i] == '--foo' || program.rawArgs[i] == '-f') {
    arguments.user = program.rawArgs[i + 1];
  }
  if (program.rawArgs[i] == '--bar' || program.rawArgs[i] == '-b') {
    arguments.pass = program.rawArgs[i + 1];
  }
}

Fail or success

With the arguments properly stored, we can now either fail or allow the script to continue with the main routine. Since we are only requiring the foo flag, we'll set the script to fail it is not supplied by the user. Otherwise, the script will continue onto the main routine.

if (!arguments.foo) {
  if (!arguments.foo) {
    console.log('Foo is required.');
  }
} else {

  console.log(arguments.foo, arguments.bar);
  ..main routine...
}

No comments:

Post a Comment