๐ŸŒ Detecting your locationโ€ฆ

How to Build a CLI Tool with Node.js in 2026: Complete Guide

โฑ๏ธ5 min read  ยท  894 words

Command-line tools automate repetitive tasks, scaffold projects, and power developer workflows. Node.js is excellent for building CLIs โ€” familiar JavaScript, a rich ecosystem, and easy npm distribution. This guide builds a complete, publishable CLI tool from scratch.

Why Build CLI Tools?

  • Automate workflows: Turn repetitive tasks into a single command
  • Distribute easily: Publish to npm, install globally with one command
  • Familiar language: JavaScript/TypeScript with a huge ecosystem
  • Cross-platform: Runs anywhere Node.js does

Project Setup

mkdir my-cli && cd my-cli
npm init -y
npm install commander chalk inquirer ora
// package.json - add the bin field and type
{
  "name": "my-cli",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "mycli": "./index.js"
  }
}

Basic CLI with Commander

#!/usr/bin/env node
// index.js - the shebang line makes it executable
import { program } from 'commander';

program
  .name('mycli')
  .description('A helpful developer CLI')
  .version('1.0.0');

program
  .command('greet')
  .description('Greet someone')
  .argument('', 'name to greet')
  .option('-l, --loud', 'shout the greeting')
  .action((name, options) => {
    const msg = `Hello, ${name}!`;
    console.log(options.loud ? msg.toUpperCase() : msg);
  });

program.parse();
# Test it locally
node index.js greet Alice
# Hello, Alice!
node index.js greet Alice --loud
# HELLO, ALICE!

Colored Output with Chalk

import chalk from 'chalk';

console.log(chalk.green('โœ“ Success!'));
console.log(chalk.red('โœ— Error occurred'));
console.log(chalk.yellow('โš  Warning'));
console.log(chalk.blue.bold('Info:'), 'processing...');

// Combine styles
console.log(chalk.bgBlue.white(' TITLE '));
console.log(chalk.dim('subtle secondary text'));

Interactive Prompts with Inquirer

import inquirer from 'inquirer';

async function setup() {
  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'projectName',
      message: 'Project name?',
      default: 'my-app',
    },
    {
      type: 'list',
      name: 'framework',
      message: 'Choose a framework:',
      choices: ['React', 'Vue', 'Svelte'],
    },
    {
      type: 'confirm',
      name: 'typescript',
      message: 'Use TypeScript?',
      default: true,
    },
  ]);

  console.log(chalk.green(`Creating ${answers.projectName} with ${answers.framework}...`));
  return answers;
}

Loading Spinners with Ora

import ora from 'ora';

async function installDeps() {
  const spinner = ora('Installing dependencies...').start();

  try {
    await runInstall();   // your async task
    spinner.succeed('Dependencies installed');
  } catch (err) {
    spinner.fail('Installation failed');
    throw err;
  }
}

A Complete Example: Project Scaffolder

#!/usr/bin/env node
import { program } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import fs from 'fs/promises';

program
  .command('create')
  .description('Scaffold a new project')
  .action(async () => {
    const answers = await inquirer.prompt([
      { type: 'input', name: 'name', message: 'Project name?' },
      { type: 'list', name: 'template', message: 'Template?',
        choices: ['api', 'web', 'cli'] },
    ]);

    const spinner = ora('Creating project...').start();
    try {
      await fs.mkdir(answers.name, { recursive: true });
      await fs.writeFile(
        `${answers.name}/package.json`,
        JSON.stringify({ name: answers.name, version: '0.1.0' }, null, 2)
      );
      spinner.succeed(chalk.green(`Created ${answers.name}!`));
      console.log(chalk.dim(`\n  cd ${answers.name}\n  npm install\n`));
    } catch (err) {
      spinner.fail('Failed to create project');
      console.error(err);
      process.exit(1);
    }
  });

program.parse();

Testing and Publishing to npm

# Link locally to test as a global command
npm link
mycli create        # test it works globally

# Unlink when done testing
npm unlink -g my-cli

# Publish to npm
npm login
npm publish

# Users install it globally
npm install -g my-cli
mycli --help

Best Practices

  • Add a shebang (#!/usr/bin/env node) so the file runs as an executable
  • Provide helpful –help output โ€” Commander generates it from your descriptions
  • Handle errors gracefully โ€” exit with non-zero codes on failure (process.exit(1))
  • Give clear feedback โ€” spinners, colors, and success/error messages
  • Support –version โ€” users expect it
  • Validate input โ€” check arguments and show useful errors

Frequently Asked Questions

Q: Commander or yargs for argument parsing?
A: Both are excellent. Commander has a clean, chainable API and is very popular. Yargs is powerful with more built-in features. For most CLIs, Commander is a great default. Try both and pick what feels natural.

Q: How do I make my CLI executable?
A: Add a shebang line (#!/usr/bin/env node) at the top of your entry file, and define the bin field in package.json mapping a command name to the file. After npm install -g (or npm link), the command is available globally.

Q: Should I use TypeScript for a CLI?
A: For larger CLIs, yes โ€” type safety helps. Compile to JavaScript before publishing (or use a bundler like tsup). For small CLIs, plain JavaScript is simpler. TypeScript pays off as the tool grows.

Q: How do I handle configuration files?
A: Read config from a file (.myclirc, package.json field, or cosmiconfig which handles multiple formats). Let users configure defaults, then override with command-line flags. cosmiconfig is the standard library for this.

Q: Can I distribute a CLI without npm?
A: Yes โ€” bundle it into a single executable with tools like pkg or Bun’s compile feature, producing a standalone binary users run without Node.js installed. Useful for wider distribution, though npm is simplest for developer audiences.

Conclusion

Building a CLI tool with Node.js is straightforward and rewarding. Use Commander for argument parsing, Chalk for colored output, Inquirer for interactive prompts, and Ora for spinners. Add a shebang line and a bin field in package.json to make it a global command, handle errors gracefully with proper exit codes, and provide clear feedback. Test locally with npm link, then publish to npm so anyone can install it with one command. CLI tools are one of the most practical things you can build โ€” they automate your workflows and, when published, help other developers too.

MD Rafikul Islam

Written by

MD Rafikul Islam is a software developer and the editor of TechPulse. He writes about developer tooling, hardware, and the practical decisions that come up in day-to-day engineering work โ€” which laptop to buy, which framework to commit to, why a build broke at 2am. He tests the tools he writes about and says plainly when something is not worth the money. Corrections and corrections requests are welcome at rony.yf25@gmail.com.

โœ๏ธ Leave a Comment

Your email address will not be published. Required fields are marked *