Table of contents

  1. 1. Code samples
  2. 2. More Features

There are many libraries to build CLI tools for Node.js like optimist, minimist, yargs, Caporal.js and commander to name just a few. In the following article Benny gives you an overview of his favorites.

Code samples

My favorite CLI builder is commander because it comes with TypeScript definitions:

commander-example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env node

import program from 'commander';

const pkg = require('../package.json');
const appName = Object.keys(pkg.bin)[0];

program
.description(pkg.description)
.name(appName)
.option('-c, --config <path>', 'set path to configuration file')
.version(pkg.version)
.parse(process.argv);

console.log('Configuration path', program.config);

Biggest lack of commander.js is that it does not fail if you have mandatory arguments but don’t supply any argument at all. For example, it fails when calling node program.js -c because there is no value for c but it doesn’t fail when just calling node program.js. Tested with commander v2.19.0. GitHub issue.

Luckily, Caporal.js addresses this issue:

caporal-example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env node

import program from 'caporal';

const pkg = require('../package.json');
const appName = Object.keys(pkg.bin)[0];

program
.version(pkg.version)
.description(pkg.description)
.name(appName)
.option('--config <config>', 'set path to configuration file', undefined, undefined, true)
.action((args, options, logger) => {
logger.info(`Configuration value: ${options.config}`);
});

program.parse(process.argv);

Should you just care about getting arguments, you will be good with minimist:

minimist-example.ts
1
2
3
import * as minimist from 'minimist';

const argv = minimist(process.argv.slice(1));

More Features