DEV Community

Duc Ng
Duc Ng

Posted on • Edited on

19 8

How to create your command-line program (CLI) with NodeJS and Commander.js

image

This post will show you how to create a command-line npm module (CLI) using Commander.js module.

Commander.js is a very popular module that lets you create your own CLI program.

First, start your new project - let's say my project name is "json-now"

$ git clone https://github.com/yourname/json-now.git
$ cd json-now
Enter fullscreen mode Exit fullscreen mode

Now, create your package.json file:

{
  "name": "json-now",
  "version": "0.0.1",
  "bin": {
    "json-now": "./bin/index.js"
  },
  "dependencies": {
    "commander": "^3.0.1"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, install dependencies:

$ npm install
Enter fullscreen mode Exit fullscreen mode

The "bin" section specifies your command line name. As you see, go ahead and create a "bin" directory with "index.js" file there:

#!/usr/bin/env node

const program = require('commander');
const ver = require('../lib/ver');
program
  .usage('[options] <file>')
  .option('-v, --version', 'show version', ver, '')
  .option('-p, --port <port>', 'use custom port')
  .option('-f, --flag', 'boolean flag', false)
  .action((file, options) => {
    console.log('file name: ', file);
    // more hanlder: require('../lib/moreHandler')(options);
  })
  .parse(process.argv);
Enter fullscreen mode Exit fullscreen mode

Let's create the very first option called "-v" or " - version" which shows version number. Create a directory named "lib" and a new file "ver.js" there:

const package = require('../package.json')
module.exports = () => {
    console.log(package.version);
};
Enter fullscreen mode Exit fullscreen mode

So far, it looks straight forward. You created a commander "program" which handles option like "-v" by running "ver.js"

Open Terminal and try it out:

$ node bin/index.js -v
0.0.1
$ node bin/index.js sample.json
file name: sample.json
Enter fullscreen mode Exit fullscreen mode

Now, it's time to publish your command line for the world to use!

$ npm login
$ npm publish

Try out your shiny new command:
$ npm install json-now -g
$ json-now -v
Enter fullscreen mode Exit fullscreen mode

The above code is located here for your reference:

https://github.com/ngduc/api-now

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay