Commander

Learn how to create interfaces for a command-line program.

Setting up the commands

If you have not heard of commander, then you should look it up. It is a great way to bootstrap your CLI application.

I think it would be good to start with an overview of the entire script, after which you will make it, step by step.

Press + to interact
const nobot = require('commander');
const { version } = require('../package');
// commands
const setup = require('./commands/setup');
const game = require('./commands/game');
const template = require('./commands/template');
nobot
.version(version);
nobot
.command('setup')
.description('clone repository dependencies')
.action(setup);
nobot
.command('game <ticketId>')
.description('create and deploy a new game reskin')
.action(game);
nobot
.command('template')
.description('release core files of template')
.option('-i, --id, [id]', 'what template to release')
.action(template);
nobot
.command('*')
.action(() => nobot.help());
nobot.parse(process.argv);
if (!process.argv.slice(2).length) {
nobot.help();
}

What you will do first is create a new program called nobot. This will be your instance of commander. I will extract the version key from package.json dynamically on the following line.

const nobot = require('commander');
const { version } = require('../package'); // e.g. 1.0.0

Next, I will require all of the commands which are found under the commands directory. At present, they will be empty JavaScript files.

// src/commands/setup.js
// src/commands/game.js
// src/commands/template.js

// commands
const setup = require('./commands/setup');
const game = require('./commands/game');
const template = require('./commands/template');

I will pass the version number, e.g. 1.0.0, to the version method on the commander instance nobot. This will output the version in the CLI.

nobot
  .version(version);

Commander allows each command to have a:

  • command identifier (e.g. setup),
  • description to explain what that command does, and
  • function to call as the action to that
...