NestJS Console Module

10.0.0 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

Demonstrates setting up a basic NestJS console application, defining a command class using `@Console`, and command methods using `@Command` and `@Option` decorators. It shows how to pass arguments and options, including type parsing, and how to bootstrap the application context for CLI execution.

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();

view raw JSON →