Search⌘ K
AI Features

Commander

Explore how to use the Commander library to build a command line interface for a Node.js build tool. Learn to configure commands such as setup, game deployment, and template releases with version control and user prompts, enhancing workflow automation.

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.

Node.js
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 command.

Each of the commands is a separate script ...