Luke Oliff.

TIL: Building a CLI Tool With commander.js in Node.js

·TIL·1 min read·Luke Oliff

A good CLI needs argument parsing, help text, and subcommands. commander.js gives you all three from a few lines of config.

#!/usr/bin/env node
const { Command } = require('commander')
const program = new Command()

program
  .name('dg')
  .description('Deepgram CLI tool')
  .version('1.0.0')

program
  .command('transcribe')
  .argument('<file>', 'audio file to transcribe')
  .option('-m, --model <name>', 'model to use', 'nova-2')
  .action((file, options) => {
    console.log(`Transcribing ${file} with ${options.model}`)
  })

program.parse()

Call it from the terminal.

node cli.js transcribe recording.wav --model nova-2

commander generates –help output, validates required arguments, and handles –version. No manual parsing of process.argv.

Does commander support async actions?

Yes. Pass an async function to .action(). commander waits for the returned Promise.

Can I add global options?

Add .option() calls directly on the program object. Global options are available on all subcommands.