{"id":17041,"library":"nestjs-console","title":"NestJS Console Module","description":"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.","status":"active","version":"10.0.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/Pop-Code/nestjs-console","tags":["javascript","nestjs","module","cli","console","commander","terminal","typescript"],"install":[{"cmd":"npm install nestjs-console","lang":"bash","label":"npm"},{"cmd":"yarn add nestjs-console","lang":"bash","label":"yarn"},{"cmd":"pnpm add nestjs-console","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for core NestJS functionalities and decorators.","package":"@nestjs/common","optional":false},{"reason":"Peer dependency for bootstrapping the NestJS application context.","package":"@nestjs/core","optional":false},{"reason":"Runtime dependency for parsing and executing CLI commands.","package":"commander","optional":false}],"imports":[{"note":"Used to register the console module in your NestJS application's root or feature module. All NestJS packages generally compile to CommonJS, but the source uses ESM syntax. Node.js v20+ is required by v10+ of this package, which leans towards ESM.","wrong":"const { ConsoleModule } = require('nestjs-console');","symbol":"ConsoleModule","correct":"import { ConsoleModule } from 'nestjs-console';"},{"note":"Decorator used to mark a class as a console command group. Its `name` property was renamed to `command` in v5.0.1.","wrong":"import { Console as NestConsole } from 'nestjs-console';","symbol":"Console","correct":"import { Console } from 'nestjs-console';"},{"note":"Decorator used to mark a method within a `@Console` class as a specific CLI command.","wrong":"import { CommandDecorator } from 'nestjs-console';","symbol":"Command","correct":"import { Command } from 'nestjs-console';"},{"note":"Injectable service for programmatic interaction with the console commands. It's a named export, not a default one.","wrong":"import ConsoleService from 'nestjs-console';","symbol":"ConsoleService","correct":"import { ConsoleService } from 'nestjs-console';"}],"quickstart":{"code":"import { Module } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { ConsoleModule, Console, Command, Option, createCommanderAction } from 'nestjs-console';\n\ninterface MyCommandOptions {\n  name: string;\n  count: number;\n}\n\n@Console({\n  command: 'app',\n  description: 'Application commands'\n})\nexport class AppConsole {\n  @Command({\n    command: 'hello <message>',\n    description: 'Says hello with a message',\n    options: [\n      { flags: '-n, --name <name>', description: 'Your name', required: true },\n      { flags: '-c, --count <count>', description: 'Number of times to say hello', defaultValue: 1, parser: (val) => parseInt(val, 10) }\n    ]\n  })\n  async hello(message: string, options: MyCommandOptions) {\n    for (let i = 0; i < options.count; i++) {\n      console.log(`Hello ${options.name || 'Stranger'}! You said: \"${message}\"`);\n    }\n    console.log(`\nEnvironment: ${process.env.NODE_ENV || 'development'}`);\n  }\n\n  @Command({\n    command: 'greet [recipient]',\n    description: 'Greets a recipient or the world'\n  })\n  async greet(recipient?: string) {\n    console.log(`Greetings, ${recipient || 'world'}!`);\n  }\n}\n\n@Module({\n  imports: [ConsoleModule.forRoot({\n    handleExceptions: true,\n    commander: createCommanderAction()\n  })],\n  providers: [AppConsole]\n})\nexport class AppModule {}\n\nasync function bootstrap() {\n  try {\n    const app = await NestFactory.createApplicationContext(AppModule, {\n      logger: ['error', 'warn'], // Only log errors and warnings for console app\n    });\n    await app.select(ConsoleModule).get(ConsoleService).init();\n    await app.close();\n  } catch (e) {\n    console.error('Console application failed to bootstrap:', e);\n    process.exit(1);\n  }\n}\n\n// To run: \n// 1. Compile: `npm run build` or `tsc`\n// 2. Execute: `node dist/console.js app hello \"How are you?\" --name Alice -c 3`\n//    or `node dist/console.js app greet Bob`\n//    or `node dist/console.js --help`\n//    Make sure 'console.ts' is set as the entry point in your tsconfig/build process.\nbootstrap();","lang":"typescript","description":"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."},"warnings":[{"fix":"Change `@Console({ name: \"myCommand\" })` to `@Console({ command: \"myCommand\" })`.","message":"The `@Console` decorator's `name` property was renamed to `command`. Update your command definitions to use `command` instead of `name`.","severity":"breaking","affected_versions":">=5.0.1"},{"fix":"Adjust command handler methods to accept an `options` object as their second parameter. Refer to the updated documentation or examples for the new signature.","message":"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.","severity":"breaking","affected_versions":">=5.0.1"},{"fix":"Upgrade your Node.js installation to version 20.0.0 or later. Use a tool like `nvm` for managing multiple Node.js versions if needed.","message":"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.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"Always install `nestjs-console` version that explicitly supports your installed NestJS and `commander` versions. Check the `nestjs-console` changelog or `package.json` peer dependencies for compatibility. Use `npm install` or `yarn add` to automatically resolve compatible versions where possible.","message":"`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.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Ensure your `tsconfig.json` `module` and `moduleResolution` settings (e.g., `NodeNext` or `Node16`) are appropriate for your project's module system. If using ESM-only dependencies, consider dynamic `import()` or configuring your NestJS project to build as ESM (though not officially supported by NestJS core).","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure 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.","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.","error":"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."},{"fix":"Check 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.","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.","error":"unknown command 'myCommand'"},{"fix":"Refactor 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()`.","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.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Ensure 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.","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).","error":"TypeError: (0 , nestjs_console_1.Console) is not a function"}],"ecosystem":"npm","meta_description":null}