nestjs-command vs nestjs-console
NestJS Command-Line Interface Libraries Comparison
1 Year
nestjs-commandnestjs-console
What's NestJS Command-Line Interface Libraries?

NestJS command-line interface libraries provide developers with tools to create and manage command-line applications within the NestJS framework. These libraries facilitate the execution of tasks, automation of processes, and management of application states directly from the terminal. They enhance the developer experience by allowing the execution of scripts, scheduled tasks, and background jobs, making it easier to manage complex applications and workflows.

Package Weekly Downloads Trend
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
nestjs-command47,671-28.9 kB-a month agoMIT
nestjs-console31,25957557.3 kB53 months agoMIT
Feature Comparison: nestjs-command vs nestjs-console

Ease of Use

  • nestjs-command:

    nestjs-command offers a simple API that allows developers to define commands with minimal configuration. It is designed for quick setup and straightforward command execution, making it ideal for small to medium-sized applications.

  • nestjs-console:

    nestjs-console provides a more extensive set of features, including built-in support for argument parsing and command options. This makes it suitable for developers who need to create more complex command-line interfaces.

Feature Set

  • nestjs-command:

    nestjs-command focuses on providing essential command execution capabilities, allowing developers to define and run commands easily. It is lightweight and does not include additional features that may complicate usage.

  • nestjs-console:

    nestjs-console includes a rich feature set, such as command grouping, middleware support, and interactive prompts. This library is designed for building robust command-line applications that require more than just basic command execution.

Extensibility

  • nestjs-command:

    While nestjs-command is relatively simple, it allows for some level of customization through decorators and command registration. However, it may not support extensive extensibility options for more complex use cases.

  • nestjs-console:

    nestjs-console is highly extensible, allowing developers to create custom commands, middleware, and hooks. This makes it a better choice for applications that require a flexible and customizable command-line interface.

Community and Support

  • nestjs-command:

    nestjs-command has a smaller community compared to nestjs-console, which may result in fewer resources and examples available for troubleshooting and learning.

  • nestjs-console:

    nestjs-console benefits from a larger community and more extensive documentation, providing developers with ample resources, examples, and community support for building command-line applications.

Learning Curve

  • nestjs-command:

    The learning curve for nestjs-command is relatively low due to its simplicity and straightforward API. Developers can quickly get started with defining and executing commands without much overhead.

  • nestjs-console:

    nestjs-console has a steeper learning curve due to its more complex feature set and additional functionalities. Developers may need to invest more time in understanding its capabilities and how to leverage them effectively.

How to Choose: nestjs-command vs nestjs-console
  • nestjs-command:

    Choose nestjs-command if you need a lightweight solution for executing simple commands and tasks within your NestJS application. It is ideal for straightforward command execution without the overhead of additional features.

  • nestjs-console:

    Choose nestjs-console if you require a more comprehensive solution with advanced features such as argument parsing, command grouping, and interactive prompts. It is suitable for building complex command-line applications with a richer set of functionalities.

README for nestjs-command

Nestjs Command

npm version npm download by month npm peer dependency version - @nestjs/core

Description

Nest.js Command tools, based on yargs.

Dependency

  • Use version 3.* for nestjs 6.*, 7.*, 8.*, 9.*, 10.*, 11.*, yargs 16.*, 17.*
  • Use version 2.* for nestjs 6.*, 7.*, 8.*, yargs 11.*, 12.*, 13.*, 14.*, 15.*
  • Use version 1.* for nestjs 6.*, 7.*
  • Use version 0.* for nestjs 5.*

BREAKING CHANGES (3.*)

In version 3.* has changes:

  • Drop: autoExit
  • Drop: CommandService.isRunning
  • Drop: CommandLogService
  • New: CommandService.exec() return Promise (Support async/await)
  • yargs only support 15.1.*, 16.*, 17.*

Installation

$ npm install --save nestjs-command yargs

# if you use typescript
$ npm install --save-dev @types/yargs

Quick Start

Register the command module in your base module: ./src/app.module.ts

import { Module } from '@nestjs/common';
import { CommandModule } from 'nestjs-command';

@Module({
  imports: [CommandModule]
})
export class AppModule {}

Create a Cli entrypoint: ./src/cli.ts

import { NestFactory } from '@nestjs/core';
import { CommandModule, CommandService } from 'nestjs-command';
import { AppModule } from './app.module';

async function bootstrap () {
  const app = await NestFactory.createApplicationContext(AppModule, {
    logger: false
  });

  try {
    await app
      .select(CommandModule)
      .get(CommandService)
      .exec();
    await app.close()
  } catch (error) {
    console.error(error);
    await app.close();
    process.exit(1);
  }
}

bootstrap();

And create your command providers (see the example below).

Run your program in either ways:

  • npx nestjs-command: run by default ./src/cli.ts
  • CLI_PATH=./dist/cli.js npx nestjs-command: run /dist/cli.js with the CLI_PATH env

Notice

Make sure to set CLI_ENV=./dist/cli.js when using commands in production with pre-compiled typescript

Usage example

Note: you will find documentation about yargs command positional here, and yargs command options here.

Create a simple Command File: ./src/user/user.command.ts

import { Command, Positional, Option } from 'nestjs-command';
import { Injectable } from '@nestjs/common';
import { UserService } from './user.service';

@Injectable()
export class UserCommand {
  constructor(private readonly userService: UserService) {}

  @Command({
    command: 'create:user <username>',
    describe: 'create a user',
  })
  async create(
    @Positional({
      name: 'username',
      describe: 'the username',
      type: 'string'
    })
    username: string,
    @Option({
      name: 'group',
      describe: 'user group (ex: "jedi")',
      type: 'string',
      alias: 'g',
      required: false
    })
    group: string,
    @Option({
      name: 'saber',
      describe: 'if user has a lightsaber',
      type: 'boolean',
      default: false,
      required: false
    })
    saber: boolean
  ) {
    this.userService.add({
      username,
      group,
      saber
    });
  }
}

Create a simple Service File: ./src/user/user.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {
  async add(user: any): Promise<any> {
    return Promise.resolve().then(() => {
      console.log('user added:', user);
    });
  }
}

Register this UserCommand and UserService as providers in your base module: ./src/app.module.ts

import { Module } from '@nestjs/common';
import { CommandModule } from 'nestjs-command';
import { UserCommand } from './user/user.command';
import { UserService } from './user/user.service';

@Module({
  imports: [CommandModule],
  providers: [UserCommand, UserService]
})
export class AppModule {}

And create a cli entrypoint: ./src/cli.ts

import { NestFactory } from '@nestjs/core';
import { CommandModule, CommandService } from 'nestjs-command';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createApplicationContext(AppModule, {
    logger: ['error'] // only errors
  });

  try {
    await app
      .select(CommandModule)
      .get(CommandService)
      .exec();
    await app.close()
  } catch (error) {
    console.error(error);
    await app.close();
    process.exit(1);
  }
}
bootstrap();

Run your program in a terminal

Get some help:

$ npx nestjs-command create:user --help
cli create:user <username>

create a user

Positionals:
  username  the username                                     [string] [required]

Options:
  -h, --help     Show help                                             [boolean]
  --saber        if user has a lightsaber             [boolean] [default: false]
  --group, -g    user group (ex: "jedi")                                [string]
  -v, --version  Show version number                                   [boolean]

Add a new user:

$ npx nestjs-command create:user anakin --group jedi --no-saber
user added: { username: 'anakin', group: 'jedi', saber: false }

$ npx nestjs-command create:user yoda --group jedi --saber
user added: { username: 'yoda', group: 'jedi', saber: true }

How to test it?

import { Test } from '@nestjs/testing';
import { CommandModule, CommandModuleTest } from 'nestjs-command';
import { AppModule } from './app.module';

describe('AppModule', () => {
  let commandModule: CommandModuleTest;

  beforeEach(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule]
    }).compile();

    const app = moduleFixture.createNestApplication();
    await app.init();
    commandModule = new CommandModuleTest(app.select(CommandModule));
  });

  it('test command module', async () => {
    const command = 'create:user <username>';
    const args = { username: 'Foo', group: 'Bar', saber: false };

    const user = await commandModule.execute(command, args);
    expect(user.username).toBe('Foo')
    expect(user.group).toBe('Bar')
  });
});