Sajith Rahim | Almanac | Blog
 
Dev

Creating CLI for your Node Script

Sajith AR
Creating CLI for your Node Script :
Explore how we can turn your existing node script into an easy-to-run CLI tool for execution via the terminal.

In this article, we’ll explore how we can turn your existing Node package into an easy-to-run Command Line Interface (CLI) tool for execution via the terminal.

Steps:

1. Add CLI script file:

  • Choose a name for your CLI script, such as cli.js and place it in the root directory or any preferred location.
  • At the top of the file, add #!/usr/bin/env node to ensure that the shell uses the Node execution context when running the package from the command line.

2. Update package.json:

  • In your package.json file, define the location of the CLI package and specify the command for invoking the program.
	
        
    
        
    
    
"bin": {
  "cli-tool": "./cli.js"
}

3. Now we need to configure command line interface;

there ar mutliple node libraries available for this, like

I’m going with Commanderjs as it’s the one I’vee used before.

You can install commander by running npm i commander.
Add commandline arguments such name as shown below. The argument may be <required> or [optional].
Add some command-line options to your script, such as --version, -t, and -d as shown below;
Ref: docs.

	
        
    
        
    
    
#!/usr/bin/env node

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

program
  .version('0.0.1') // version
  .argument('<name>') // required argument
  .option('-t, --title <honorific>', 'title to use before name') // option
  .option('-d, --debug', 'display some debugging') // option boolean
  .action((name, options, command) => {
    // logic goes here
  });

program.parse();

4. Implement the CLI logic.

	
        
    
        
    
    
#!/usr/bin/env node

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

program
  .version('0.0.1')
  .argument('<name>')
  .option('-t, --title <honorific>', 'title to use before name')
  .option('-d, --debug', 'display some debugging')
  .action((name, options, command) => {
    if (options.debug) {
      console.error('Called %s with options %o', command.name(), options);
    }
    const title = options.title ? `${options.title} ` : '';
    console.log(`Thank-you ${title}${name}`);
  });

program.parse();

To test it out, follow the instructions below:

  1. Run npm link from the root directory of your package.
  2. Test the CLI tool by running cli-tool --V or cli-tool Doe --title Mr

You have successfully created a basic Node CLI tool!


CONNECT

 
Have something to share,
Let's Connect