Build a CLI Tool with Node.js in 2026
Building CLI tools is one of the most satisfying things you can do as a developer. A well-crafted CLI tool can save you and your team hours of repetitive work. Here is how to build one from scratch using modern Node.js tooling.
Project Setup
Create a new project with TypeScript and ESM modules. Use tsx for development (fast TypeScript execution without compilation) and tsup for building (produces optimized CJS and ESM bundles). Add a bin field in package.json pointing to your entry script with a hashbang line. This tells npm to create an executable when your package is installed globally.
Argument Parsing
Use commander or yargs for argument parsing. Define commands, options, and arguments with type-safe builders. Add --help generation, version flags, and bash completion. For complex CLIs with subcommands, organize each command in its own file and register them with the main program. Always provide sensible defaults for optional arguments.
User Interface
Use chalk for colored output, ora for spinners, and cli-table3 for tabular data. Show progress bars for long operations with cli-progress. Use prompts (via inquirer or @clack/prompts) for interactive input when arguments are not provided. Always support a --json flag for machine-readable output so your CLI can be used in scripts and pipelines.
Error Handling
Catch all errors and display user-friendly messages. Show the error message in red, suggest possible fixes, and include a --verbose flag for full stack traces. Exit with appropriate exit codes: 0 for success, 1 for general errors, 2 for usage errors. Handle SIGINT (Ctrl+C) gracefully by cleaning up temporary files and restoring terminal state.
Testing and Distribution
Test your CLI with vitest by importing command handlers directly and testing them as functions. For integration tests, use execa to run the CLI as a subprocess and assert on stdout and exit codes. Publish to npm with proper package.json metadata including description, keywords, repository, and files. Add a GitHub Action that publishes on version tags automatically.
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.