Backend Development 2 min read 721 views

Building CLI Tools with Node.js: From Simple Scripts to Complex Applications

Create powerful CLI tools with Node.js using Commander.js and Inquirer. Learn about argument parsing, interactive prompts, and distribution.

Terminal command line

Building CLI Tools with Node.js

Create powerful command-line tools for automation and productivity.

Project Setup

mkdir my-cli && cd my-cli
npm init -y
npm install commander inquirer chalk ora

// package.json
{
    "name": "my-cli",
    "bin": {
        "mycli": "./bin/index.js"
    }
}

Basic CLI Structure

#!/usr/bin/env node
// bin/index.js

const { program } = require('commander');
const chalk = require('chalk');

program
    .name('mycli')
    .description('My awesome CLI tool')
    .version('1.0.0');

program
    .command('greet <name>')
    .description('Greet someone')
    .option('-l, --loud', 'Say it loudly')
    .action((name, options) => {
        const greeting = `Hello, ${name}!`;
        console.log(options.loud ? chalk.bold.green(greeting.toUpperCase()) : greeting);
    });

program.parse();

Interactive Prompts

const inquirer = require('inquirer');

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

    return answers;
}

Progress Indicators

const ora = require('ora');

async function downloadFiles() {
    const spinner = ora('Downloading files...').start();

    try {
        await download();
        spinner.succeed('Download complete!');
    } catch (error) {
        spinner.fail('Download failed');
        process.exit(1);
    }
}

Publishing to npm

npm login
npm publish

CLI tools are excellent for automating repetitive tasks and improving developer workflows.

Share this article:
ES
Written by

Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!

Related Articles

Related Articles

Need Help With Your Project?

Book a free 30-minute consultation to discuss your technical challenges and explore solutions together.