How to Build CLI Tool in Node.js

Building CLI tool in NodeJs

CLI (Command-line interface) is the most common way to run a program in a terminal. As a software engineer, you’ll come across different CLIs every day namely git, Docker & npm etc.

Today we’ll be sharing a few helpful packages & our knowledge on building CLIs using Node.js.

Our ultimate goal would be to have something similar to the one shown below:-

npm install -g bluerain
bluerain

npm setup

First of all, you want to make sure that you have a proper npm configuration and folder structure.

bin/index.js:

#!/usr/bin/env node
//execute the code of cli here e.g
console.log('Welcome to bluerain cli tool');

The snippet above should look very simple — all we need is the main file (or entry point) of the app.

package.json:

{
"name": "bluerain-cli",
"version": "0.1.2",
"main": "bin/index.js",
"bin": {
"bluerain": "bin/index.js"
},
}

Important things in the package.json are the following:-

  • name: for naming in npm ecosystem.
  • version: upon alteration of your program, you’ll have to update its version and publish it.
  • main: denotes an entry point.
  • bin.bluerain: should direct to our bin/index.js file. Also, this name is going to be utilized after the installation as a terminal command for the program.

The bin in package.json is also important to understand. In the bin, object key is denoted as the name of our cli tool and value is the path of the file to be run when bluerain is entered in terminal. The code present in bin/index.js will be executed as node bin/index.js command when bluerain is entered in the terminal.

Inquirer package can be employed for common interactive command line user interfaces. https://github.com/SBoudrias/Inquirer.js/