Caporal CLI Framework
Caporal is a comprehensive framework for building command-line interface (CLI) applications with Node.js. It offers robust features for defining commands, parsing arguments, and handling options, along with automated help generation, colorful output, adjustable verbosity, and custom logging. Distinguishing features include built-in type coercion (e.g., `prog.INT`), intelligent typo suggestions for commands, and shell auto-completion capabilities for Bash, Zsh, and Fish. The current stable version is 3.1.5, released in August 2023, succeeding the major 3.0.0 release which introduced updated Node.js compatibility requirements. The project maintains an active development pace, with regular patch and minor updates focused on bug fixes and feature enhancements.
Common errors
-
Error: Cannot find module 'caporal'
cause The Caporal package is not installed or the Node.js module resolver cannot find it.fixRun `npm install caporal` or `yarn add caporal` in your project directory. -
ReferenceError: prog is not defined
cause This typically occurs when mixing module systems (e.g., using `require()` in an ES Module context or `import` in a CommonJS context) or when the imported symbol name doesn't match the export.fixFor ES Modules/TypeScript, use `import * as prog from 'caporal';`. For CommonJS, use `const prog = require('caporal');`. Ensure your project's `package.json` `"type": "module"` is set correctly for ESM. -
This module requires Node.js >= 16. Current version: vX.Y.Z
cause You are attempting to use Caporal v3.x or newer with a Node.js version below the minimum requirement of 16.fixUpgrade your Node.js environment to version 16 or higher using a tool like `nvm` or by installing a newer version directly.
Warnings
- breaking Caporal v3.0.0 introduced a breaking change by dropping support for Node.js versions older than 16. Applications running on Node.js < 16 will fail to run or install when upgrading to Caporal v3.x.
- gotcha When defining variadic arguments (e.g., `...items`), they must always be the last argument specified for a command. Placing them anywhere else will lead to incorrect parsing behavior or errors.
- gotcha Recent v3.1.x releases (specifically 3.1.5) indicate fixes related to module exports. Users might encounter issues with imports or module resolution depending on their build setup or specific Node.js version, especially when transitioning between Caporal versions or module systems.
Install
-
npm install caporal -
yarn add caporal -
pnpm add caporal
Imports
- program
import prog from 'caporal';
import * as prog from 'caporal';
- program (CJS)
import * as prog from 'caporal';
const prog = require('caporal'); - INT (Type Coercion)
prog.INT
Quickstart
#!/usr/bin/env node
import * as prog from 'caporal';
prog
.version('1.0.0')
.description('A simple deployment CLI application')
.command('deploy', 'Deploy an application to a specified environment')
.argument('<appName>', 'The name of the application to deploy', /^myapp|their-app$/)
.argument('[environment]', 'The target environment (dev, staging, production)', /^dev|staging|production$/, 'local')
.option('--tail <lines>', 'Tail log lines after deployment', prog.INT, 10)
.option('--force', 'Force deployment even if warnings exist', prog.BOOL, false)
.action(async (args, options, logger) => {
const { appName, environment } = args;
const { tail, force } = options;
logger.info(`Deploying application: ${appName}`);
logger.info(`Target environment: ${environment}`);
logger.info(`Tail ${tail} log lines: ${tail > 0}`);
logger.info(`Force deploy: ${force}`);
if (force) {
logger.warn('Forcing deployment, ignoring warnings...');
}
// Simulate deployment process
await new Promise(resolve => setTimeout(resolve, 1500));
logger.info(`Application '${appName}' deployed to '${environment}' successfully.`);
if (tail > 0) {
logger.info(`Tailing last ${tail} log lines...`);
// Simulate log tailing
for (let i = 1; i <= tail; i++) {
logger.info(`[${new Date().toISOString()}] Log line ${i}`);
}
}
});
prog.parse(process.argv);