Make Your Own CLI Command Using Node.js: A Step-by-Step Guide

1. Setting Up the Project

To begin, insure you haveNode.js installed on your system if not use the below link to of sanctioned nodejs point to download

Download nodejs

now produce a new design directory and open this directory in your CMD run the below command

 npm init

This command will guide you through setting up the introductory details of your design and induce the package.json file. coming step you have to install 2 packages express.js and commander.js and below are cli commands to install it

npm install express
npm install commander

3. Building the CLI Command

Now comes the instigative part – erecting your custom CLI command! produce a new 2 JavaScript lines index.js and cli.js.

Now put this code in your index.js

const express = require('express');
const app = express();

app.listen(4000, function () { 
    console.log('Server connected');
})

in this code, we’re just importing an express package, and app variable is a case of Express operation by calling the express() function. app variable will be used to define garçon configuration. app.listen function touched off an express application to start listing for forthcoming connections on 4000 ports. The listen() system sets up the web garçon to hear on the specified harborage for any incoming HTTP requests.

now we start using commnader.js package, open your cli.js file, and bury this below code

const { program } = require('commander');


program
  .command('command statement  ')
  .description('Command description')
  .action(() => {
    
  });

program.parse(process.argv);

above code originally import commander package and used one of his cases called program. program case has a property called command, command is function and it take one string argument, this string it self a command that we gon na run in cli. coming property is description serve it also takes one string argument for command description and last property we use called action function it one message function as argument. In this message function, we define we this command gon na do when command hit in cli.
At last we use another property of program called parse, in this function we pass CL arguments array using process( GLOBAL object innode.js).

4. Adding Functionality to the Command

Next, let’s add functionality in CLI command. Define the conduct you want the command to perform when invoked. let say we want to make a command to induce regulator file( MVC reference) and also pass file name in command. See below Code!

const fs = require('fs');
const path = require('path');
const { program } = require('commander');

// Configure the command-line options and actions
program
  .command('create-controller <controllerName>')
  .description('Create a controller file and include it in index.js')
  .action((controllerName) => {
    const filename = `${controllerName}Controller.js`
    createControllerFile(controllerName, filename);
  });


// Function to create the controller file
const createControllerFile = (controllerName, filename) => {
  const controllerCode = `
    this is your controller file
  `;

  const filePath = path.join(__dirname, filename);

  fs.writeFile(filePath, controllerCode, (error) => {
    if (error) {
      console.error(`Error creating controller file: ${error}`);
      return;
    }

    console.log(`Controller file "${filename}" created successfully.`);

  });
};


program.parse(process.argv);

to induce file first we import fs package for file creation next we need to import path for generating file path and as usual ‘ program ’ case from commander package.
now using program parcels called command function passing command statement as string and mentioning 1 thing then when we want to pass dynamic value in command we use ” ” this sign this dynamic value entered in action message function as an argument you can pass multiple argument using this ” “.
In action message we make file name just concatenating “controller.js ” string with regulator argument which we pass in command. next we calling createControllerFile() function in this function ‘ controllerCode ’ is variable in which we store regulator file data which we wan na write in regulator file. coming step we making a file path where we want to store that file. coming step fs package functionality to induce file.

5. Run CLI Custom Command

To run your custom command run this command on you CMD .

node cli.js create-controller User

node is keyword, cli.js is file name where we write our custom command code,

  • node is keyword
  • cli.js is file name where we write our custom command code
  • create-controller is keywords that mention in command function
  • user is file name

after run this command 1 file is created on your root directory called UserController.js

7. Adding NPM Package and Publishing

Once your custom CLI command is ready and completely tested, you can do to publish it as an NPM package. This allows other inventors to install and use your CLI encyclopedically, adding to its mileage and fashionability.

8. Conclusion

Congratulations! Successfully making your own CLI command. By following this companion, you ’ve learned how to streamline your development workflow, boost productivity, and save precious time.

FAQ’s

Can I use my custom CLI command across different projects?

Absolutely! Once you publish your CLI command as an NPM package, you can install and use it in any Node.js project globally.

Can I share my custom CLI command with the community?

Yes, by publishing it as an NPM package, you make your CLI command available for others to discover, use, and contribute to.

Can I update my CLI command after publishing it?

Certainly! You can release new versions of your CLI command with improvements and bug fixes.

What if I encounter issues while building my CLI command?

Don’t worry! If you face any challenges, you can refer to the official Node.js and NPM documentation or seek help from the vibrant developer community.

Leave a Comment