NestJS Console Module
nestjs-console is a NestJS module that provides a command-line interface (CLI) for NestJS applications. It enables developers to define and run console commands within the application's dependency injection context, which is particularly useful for tasks such as headless operations, cron jobs, data processing, and migrations. The module integrates with the popular `commander.js` package for robust command parsing and execution. It bootstraps a `NestApplicationContext` (headless) rather than a full `NestApplication`, ensuring that CLI commands have access to all necessary NestJS services without initiating an HTTP server. The current stable version is 10.0.0, which supports NestJS v11, Commander v12 & v13, and requires Node.js >= v20.0.0. Its release cadence is closely tied to major NestJS and Commander updates. A key differentiator is its seamless integration with NestJS's decorators and DI system, allowing command logic to reside directly within NestJS providers.
Common errors
-
Error: Nest can't resolve dependencies of the [YourConsoleClass] (?). Please make sure that the argument [dependency] at index [index] is available in the [YourModule] context.
cause A dependency required by your `@Console` decorated class (or one of its injected services) is not properly provided within the module where `AppConsole` is listed as a provider, or within its imported modules.fixEnsure all services, modules, or providers that `YourConsoleClass` depends on are correctly imported into `AppModule` (or any module that provides `YourConsoleClass`). Verify `providers` and `imports` arrays in your `@Module` decorator. -
unknown command 'myCommand'
cause The command you are trying to execute is not recognized by `nestjs-console`. This typically means the `AppConsole` class or its methods are not correctly decorated or registered.fixCheck that your console class has the `@Console` decorator, your command methods have the `@Command` decorator, and that your console class is listed in the `providers` array of your `AppModule` or an imported module. -
ReferenceError: require is not defined in ES module scope
cause You are attempting to use a CommonJS `require()` call in an ES module context. This often happens in Node.js >= 14 projects configured for ESM, or when mixing CJS and ESM modules incorrectly.fixRefactor your imports to use ES module `import` syntax. If you need to import a CommonJS module in an ESM context, Node.js typically handles it, but for ESM-only modules in a CommonJS context, you might need dynamic `import()`. -
TypeError: (0 , nestjs_console_1.Console) is not a function
cause This error usually indicates an incorrect import statement for the `Console` decorator or that the module was loaded incorrectly (e.g., using `require` for a module primarily designed for ES imports and decorators).fixEnsure you are using `import { Console } from 'nestjs-console';` and that your `tsconfig.json` correctly processes decorators and modules. Verify your Node.js version meets the package requirements.
Warnings
- breaking The `@Console` decorator's `name` property was renamed to `command`. Update your command definitions to use `command` instead of `name`.
- breaking The signature of command handler methods changed in v5.0.1. Options are now passed directly as the second argument to the handler method, rather than being accessed implicitly.
- breaking Version 10.0.0 of `nestjs-console` requires Node.js version 20.0.0 or higher. Previous versions required Node.js v16+ for NestJS v10. Ensure your Node.js environment meets this minimum requirement.
- breaking `nestjs-console`'s major versions are coupled with NestJS and `commander` major versions. For example, v10 supports NestJS v11 and Commander v12/13, while v9 supported NestJS v10 and Commander v11. Mismatching versions can lead to peer dependency conflicts and runtime errors.
- gotcha NestJS typically compiles to CommonJS modules, even when using ESM syntax. While Node.js v20+ has better ESM support, dynamic `import()` might be needed for ESM-only packages in some NestJS setups. Directly `require()`ing ESM-only modules in a CJS context will cause errors.
Install
-
npm install nestjs-console -
yarn add nestjs-console -
pnpm add nestjs-console
Imports
- ConsoleModule
const { ConsoleModule } = require('nestjs-console');import { ConsoleModule } from 'nestjs-console'; - Console
import { Console as NestConsole } from 'nestjs-console';import { Console } from 'nestjs-console'; - Command
import { CommandDecorator } from 'nestjs-console';import { Command } from 'nestjs-console'; - ConsoleService
import ConsoleService from 'nestjs-console';
import { ConsoleService } from 'nestjs-console';
Quickstart
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ConsoleModule, Console, Command, Option, createCommanderAction } from 'nestjs-console';
interface MyCommandOptions {
name: string;
count: number;
}
@Console({
command: 'app',
description: 'Application commands'
})
export class AppConsole {
@Command({
command: 'hello <message>',
description: 'Says hello with a message',
options: [
{ flags: '-n, --name <name>', description: 'Your name', required: true },
{ flags: '-c, --count <count>', description: 'Number of times to say hello', defaultValue: 1, parser: (val) => parseInt(val, 10) }
]
})
async hello(message: string, options: MyCommandOptions) {
for (let i = 0; i < options.count; i++) {
console.log(`Hello ${options.name || 'Stranger'}! You said: "${message}"`);
}
console.log(`
Environment: ${process.env.NODE_ENV || 'development'}`);
}
@Command({
command: 'greet [recipient]',
description: 'Greets a recipient or the world'
})
async greet(recipient?: string) {
console.log(`Greetings, ${recipient || 'world'}!`);
}
}
@Module({
imports: [ConsoleModule.forRoot({
handleExceptions: true,
commander: createCommanderAction()
})],
providers: [AppConsole]
})
export class AppModule {}
async function bootstrap() {
try {
const app = await NestFactory.createApplicationContext(AppModule, {
logger: ['error', 'warn'], // Only log errors and warnings for console app
});
await app.select(ConsoleModule).get(ConsoleService).init();
await app.close();
} catch (e) {
console.error('Console application failed to bootstrap:', e);
process.exit(1);
}
}
// To run:
// 1. Compile: `npm run build` or `tsc`
// 2. Execute: `node dist/console.js app hello "How are you?" --name Alice -c 3`
// or `node dist/console.js app greet Bob`
// or `node dist/console.js --help`
// Make sure 'console.ts' is set as the entry point in your tsconfig/build process.
bootstrap();