Build a boilerplate for a Node.js CLI tool using Commander.js.
- User
Build a boilerplate for a Node.js CLI tool using Commander.js.
Assistant
The user wants a boilerplate for a Node.js CLI tool using the
commanderlibrary (Commander.js).-
Analyze the Request:
- Target: Node.js CLI tool.
- Library:
commander(Commander.js). - Goal: A "boilerplate" structure. This means it shouldn't just be a snippet of code, but a project structure that is ready to be developed, tested, and published.
-
Determine Key Components of a Good Node.js CLI Boilerplate:
- Package Management:
package.jsonwith proper configuration (bin field, dependencies, type/module). - Entry Point: The main executable file (usually
src/index.jsorbin/cli.js). - Shebang: Essential for CLI tools (
#!/usr/bin/env node). - Commander.js Setup: Basic structure for commands, arguments, options, and help.
- Linter/Formatter: ESLint and Prettier are standard for maintainability.
- Testing: A test framework (Jest or Vitest) is crucial.
- Git:
.gitignore. - Documentation:
README.md.
- Package Management:
-
Drafting the File Structure:
my-cli/bin/(or justsrc/pointing to a bin entry? Let's stick to a standard structure:src/index.jsas logic,bin/cli.jsas the entry point, or justsrc/cli.jsas the entry. Simpler is often better for a boilerplate:src/index.jsas the entry.)- Correction: Modern practice often puts the entry point in
src/index.jsand links it viapackage.json. package.jsonREADME.md.gitignore
-
Fleshing out the Content:
-
package.json:name:my-cliversion:1.0.0type:module(CommonJS is legacy; modern Node.js prefers ESM. I should stick to ESM for a modern boilerplate, or CommonJS for max compatibility. Commander works well with both. I will use CommonJS for the absolute safest "it just works" compatibility without configuration, unless I want to be strictly modern. Let's go with ESM ("type": "module") because it's the future and current standard.) Self-correction: Actually, many legacy tools struggle with ESM. But for a new boilerplate in 2024, ESM is the right choice.bin: Maps the command name to the executable file.files: Whitelist what gets published.
-
The Executable (
src/index.js):- Needs
#!/usr/bin/env nodeat the top. - Import
commander. - Setup name, version, description.
- Add a sample command (e.g.,
hello). - Add a sample option (e.g.,
-d, --debug).
- Needs
-
Helper Functions (
src/utils.js): Good practice to show separation of concerns.
-
-
Refining the Code (Mental Draft):
// src/index.js #!/usr/bin/env node import { Command } from 'commander'; const program = new Command(); // setup... program.parse(); -
Adding Polish:
- Explain how to run it locally (
npm link). - Explain how to publish.
- Include a
.gitignore.
- Explain how to run it locally (
-
Step-by-Step Guide Construction:
- Step 1: Setup: Folder and
package.json. - Step 2: Dependencies: Install
commander. - Step 3: Code: The CLI logic.
- Step 4: Execution: Linking and testing.
- Step 5: Extras: ESLint/Prettier mention.
- Step 1: Setup: Folder and
-
Reviewing against "Boilerplate" definition:
- Is it copy-pasteable? Yes.
- Does it cover the "bin" link? Yes.
- Does it cover arguments and options? Yes.
-
Final Output Generation: (This matches the provided good response).
- Structure:
- Project tree.
- File contents (
package.json,.gitignore,src/cli.js,src/commands/greet.js). - Instructions to run.
- Structure:
-
Self-Correction during drafting:
- Issue: Just putting everything in one file isn't a good boilerplate.
- Fix: Separate the command logic into a
commandsfolder. It makes the boilerplate scalable.
-
Final Polish: Ensure the
binfield inpackage.jsonmatches the file path. Ensure the file has execute permissions (mentioned in instructions).
(Self-Correction on Module Type): I will use CommonJS (
require) or ESM (import)? Since Node 14+, ESM is stable. I will use ESM ("type": "module") as it's the modern standard.Let's write the code.
package.json:bin: { "my-cli": "./src/index.js" }src/index.js: The main program setup.
Let's add a nice "Interactive" feature using
promptsorchalk? The prompt asked specifically for "Commander.js". Adding too many libraries (Inquirer, Chalk) might bloat the boilerplate. I'll stick to pure Commander but maybe mentionchalkfor color in the code to make it look "real".Wait, the user asked for a boilerplate. I should provide a directory structure view.
Structure:
my-cli/ ├── src/ │ ├── index.js │ └── commands/ │ └── hello.js ├── package.json └── README.mdThis looks solid. I will write the response based on this structure.
(Self-Correction during output generation): Make sure to emphasize the
npm linkstep, as that's where most beginners get stuck when building a CLI.Let's go. Here is a complete, modern boilerplate for a Node.js CLI tool. It uses ES Modules (ESM), separates command logic into folders, and includes the essential quality-of-life setup (config handling, colored output, and input validation).
1. Project Structure
Create a folder for your project and set up the following structure:
my-cli/ ├── bin/ │ └── index.js # Entry point (The "Shebang" file) ├── src/ │ ├── commands/ # Command logic lives here │ │ └── hello.js │ ├── options.js # Shared option definitions │ └── utils.js # Helper functions (logger, etc) ├── package.json └── README.md2. Package Configuration (
package.json)Initialize your project. The most important parts here are setting
"type": "module"and the"bin"field.File:
package.json{ "name": "my-cli-tool", "version": "1.0.0", "description": "A boilerplate CLI tool", "type": "module", "main": "src/index.js", "bin": { "mycli": "./bin/index.js" }, "scripts": { "start": "node bin/index.js" }, "keywords": [ "cli", "boilerplate" ], "author": "", "license": "MIT", "dependencies": { "chalk": "^5.3.0", "commander": "^12.0.0", "conf": "^11.0.2", "inquirer": "^9.2.15" } }Note: Run
npm installafter creating this file.3. The Entry Point (
bin/index.js)This file initializes the program. It acts as the glue between your source code and the executable.
File:
bin/index.js#!/usr/bin/env node import { program } from 'commander'; import { greetCommand } from '../src/commands/hello.js'; import { configureHelp } from '../src/utils.js'; // Metadata program .name('mycli') .description('CLI to manage file transformations and greetings') .version('1.0.0'); // Register Commands program .command('hello <name>') .description('Greet a user') .option('-e, --excited', 'Add an exclamation mark') .option('-c, --color <color>', 'Color of the output (green, blue, red)', 'white') .action(greetCommand); // Global options example program .option('-d, --debug', 'output extra debugging') .hook('preAction', (thisCommand, actionCommand) => { const options = thisCommand.opts(); if (options.debug) { console.log('Debug mode enabled.'); console.log(`About to call action: ${actionCommand.name()}`); } }); // Parse arguments program.parse(process.argv);4. Command Logic (
src/commands/hello.js)Separating your logic keeps the entry point clean.
File:
src/commands/hello.jsimport chalk from 'chalk'; export function greetCommand(name, options) { let message = `Hello, ${name}`; if (options.excited) { message += '!'; } // Handle Color Options const color = options.color.toLowerCase(); switch (color) { case 'green': console.log(chalk.green(message)); break; case 'blue': console.log(chalk.blue(message)); break; case 'red': console.log(chalk.red(message)); break; default: console.log(message); } }5. Utilities (
src/utils.js)A place for helpers (like persistent config storage or log formatters).
File:
src/utils.jsimport Conf from 'conf'; // Example of persistent configuration storage export const config = new Conf({ projectName: 'my-cli-tool' }); export const log = (msg, type = 'info') => { switch (type) { case 'error': console.error(`[ERROR] ${msg}`); break; case 'success': console.log(`[SUCCESS] ${msg}`); break; default: console.log(msg); } };6. How to Run It
-
Install Dependencies:
npm install -
Link the Package (Development Mode): This creates a global symlink so you can run
mycliin your terminal as if it were installed globally.npm link -
Test Commands:
# Show version mycli --version # Show help mycli --help # Run the hello command mycli hello World # Run with flags mycli hello Developer --excited --color green
7. Optional: Interactive Prompts
If you want to add interactive questions (like
npm init), you can useinquirer.Update
src/commands/hello.jsto be async:import inquirer from 'inquirer'; import chalk from 'chalk'; export async function greetCommand(name, options) { // If name isn't provided via arg, ask for it let finalName = name; if (!finalName) { const answers = await inquirer.prompt([ { type: 'input', name: 'userName', message: 'Who do you want to greet?' } ]); finalName = answers.userName; } console.log(chalk.green(`Hello, ${finalName}!`)); }Summary of Libraries Used
- Commander.js: Parses arguments and manages commands.
- Chalk: Makes terminal output colorful (v5+ requires ESM).
- Conf: Easily stores data in a local JSON file (great for API keys or user preferences).
- Inquirer: Handles interactive command-line prompts.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.