DEV Community

Orbit Websites
Orbit Websites

Posted on

Building CLI Tools with Node.js: A Practical Guide

Building CLI Tools with Node.js: A Practical Guide

As developers, we've all been there - struggling to automate repetitive tasks or streamline our workflows. That's where CLI tools come in. A well-crafted CLI tool can save us hours of time and make our lives easier. In this article, we'll explore how to build CLI tools with Node.js, a popular choice for this task.

Setting Up Your Project

Before we dive into the nitty-gritty, let's set up a new project. Create a new directory for your project and initialize a new Node.js project using npm init. This will create a package.json file that we'll use to manage our dependencies.

mkdir my-cli-tool
cd my-cli-tool
npm init -y
Enter fullscreen mode Exit fullscreen mode

Next, install the yargs package, which will help us parse command-line arguments. We'll also install chalk for colorful output.

npm install yargs chalk
Enter fullscreen mode Exit fullscreen mode

Parsing Command-Line Arguments

yargs makes it easy to parse command-line arguments. Let's create a simple example that takes a --name argument.

const yargs = require('yargs');
const chalk = require('chalk');

const argv = yargs
  .option('name', {
    alias: 'n',
    type: 'string',
    demandOption: true,
    describe: 'Your name',
  })
  .help()
  .argv;

console.log(chalk.green(`Hello, ${argv.name}!`));
Enter fullscreen mode Exit fullscreen mode

In this example, we use yargs.option() to define a new option called name. We specify the alias n and the type string. We also set demandOption to true, which means that the user must provide a value for this option.

Handling Errors and Validation

When building CLI tools, it's essential to handle errors and validate user input. Let's update our previous example to include some basic error handling.

const yargs = require('yargs');
const chalk = require('chalk');

const argv = yargs
  .option('name', {
    alias: 'n',
    type: 'string',
    demandOption: true,
    describe: 'Your name',
  })
  .help()
  .argv;

try {
  if (!argv.name) {
    throw new Error('Please provide a name');
  }

  console.log(chalk.green(`Hello, ${argv.name}!`));
} catch (error) {
  console.error(chalk.red(error.message));
  process.exit(1);
}
Enter fullscreen mode Exit fullscreen mode

In this updated example, we use a try-catch block to catch any errors that might occur. If the user doesn't provide a name, we throw an error with a helpful message. We also use process.exit(1) to exit the process with a non-zero status code, indicating that something went wrong.

Creating a CLI Tool with Multiple Commands

As our CLI tool grows, we might want to add multiple commands. Let's create a simple example that includes two commands: hello and goodbye.

const yargs = require('yargs');
const chalk = require('chalk');

const argv = yargs
  .command('hello', 'Say hello to someone', (yargs) => {
    yargs.option('name', {
      alias: 'n',
      type: 'string',
      demandOption: true,
      describe: 'Their name',
    });
  })
  .command('goodbye', 'Say goodbye to someone', (yargs) => {
    yargs.option('name', {
      alias: 'n',
      type: 'string',
      demandOption: true,
      describe: 'Their name',
    });
  })
  .help()
  .argv;

switch (argv._[0]) {
  case 'hello':
    try {
      if (!argv.name) {
        throw new Error('Please provide a name');
      }

      console.log(chalk.green(`Hello, ${argv.name}!`));
    } catch (error) {
      console.error(chalk.red(error.message));
      process.exit(1);
    }
    break;
  case 'goodbye':
    try {
      if (!argv.name) {
        throw new Error('Please provide a name');
      }

      console.log(chalk.red(`Goodbye, ${argv.name}!`));
    } catch (error) {
      console.error(chalk.red(error.message));
      process.exit(1);
    }
    break;
  default:
    console.error(chalk.red('Unknown command'));
    process.exit(1);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we use yargs.command() to define two new commands: hello and goodbye. We then use a switch statement to handle the different commands.

Conclusion

Building CLI tools with Node.js is a powerful way to automate tasks and streamline workflows. By using yargs and chalk, we can create robust and user-friendly CLI tools. Remember to handle errors and validate user input to ensure a smooth experience for your users. With these practical tips and code snippets, you're ready to start building your own CLI tools. Happy coding!


Appreciative

Top comments (0)