Consider your project's nature: a versatile CLI designed for seamless terminal use. It stands alone, responsive to calls. In case my answer here does not fit you well you can try my Step by Step NestJs Commander.
First you need to create a command class for example here command-tutorial.ts
import { CommandRunner, Command, Option } from 'nest-commander';
@Command({
name: 'basic',
arguments: '[task]',
description: 'A parameter parse',
})
export class CommandTutorial extends CommandRunner {
constructor() {
super();
}
async run(
passedParams: string[],
options?: Record<string, any>,
): Promise<void> {
console.log('CLI Params', passedParams);
console.log('CLI Options', options);
return Promise.resolve(undefined);
}
@Option({
flags: '-n, --number [number]',
description: 'A basic number parser',
})
parseNumber(val: string): number {
return Number(val);
}
}
then inside the app.module.ts import this command
import { Module } from '@nestjs/common';
import { CommandTutorial } from './command-tutorial';
@Module({
imports: [],
controllers: [],
providers: [CommandTutorial],
})
export class AppModule {}
inside your main.ts you need to add the shebang on the top of you of your code and plus change the bootstrap function
#!/usr/bin/env node
import { AppModule } from './app.module';
import { CommandFactory } from 'nest-commander';
async function bootstrap() {
await CommandFactory.run(AppModule, {
logger: ['warn', 'error'],
});
}
bootstrap();
for testing your app it is so easy just run the following command
ts-node main.ts basic argument -n 1
and check the result inside your CMD
now to run it with a terminal prompt you need to update your package.json and add the bin script
"bin": {
"tutorial": "dist/main.js"
}
or
"bin": {
"tutorial": "./dist/main.js"
}
"tutorial" will be your command you can change it to whatever you want
and run the following command chmod +x ./dist/main.js (MAC OS check it is alternative in Windows/Unix)
then inside your NodeJs Project or NestJs Project install this as module using
- npm i path-to-your-nest-command-cli-directory
if you would like to be globally inside your machine
- npm i g path-to-your-nest-command-cli-directory
Now run tutorial basic argument -n 1 inside your cmd or terminal you should get
CLI Params: argument
CLI Option: {n:1}
All the best
crun runto run the command, but when I try using crun, it doesn't recognize the command!crunname.bininpackage.json. Also, read the docs: nest-commander.jaymcdoniel.dev/docs/executing/localnode ./dist/main [args] [options]running this command wound't just run my app? (it just did, but I might be a bit stupid, sorry), like:node ./dist/main sayHellojust run my app