Create CLI application in NodeJS

Shubham Verma
2 min readJul 31, 2018

--

In this application, I will create a CLI-based application. It means you will interact only with the Node CLI.

Now I am going to make a simple add application to add the number(s). I will also implement error handling within this application.

So let’s start.

Instantiate the readline module:

 var readline = require(‘readline’);

The above module will help us to create an interface for the CLI application.

Instantiate the CLI Module object:

var cli = {};

Now create the CLI functions as:

cli.processInput = function (str) {
str = typeof (str) == ‘string’ && str.trim().length > 0 ? str.trim() : false;
if (str) {
var inputs = str.split(‘ ‘);
if (inputs.length >= 3) {
var results = 0;
inputs.some(function (value) {
if (!isNaN(value)) {
results = results + parseInt(value);
}
})
console.log(“\x1b[36m”,”Total is :”,results);
return true;
} else {
console.error(“\x1b[31m”,”Error: Too few parameter”);
return false;
}
}
}

Create an init script to start the CLI application:

cli.init = function () {
/* Send the start message to the console in dark blue. */
console.log(‘\x1b[33m%s\x1b[0m’, ‘CLI is running’);
/* Start the interface */
var _interface = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: ‘>’
})
/* Create an initial prompt */
_interface.prompt(); // Will wait for input
/* Handle each line of input separately. */
_interface.on(‘line’, function (str) {
/* Send to input processor. */
cli.processInput(str);
/* re-initialize the prompt afterwards. */
_interface.prompt();
});
}

Now start the script:

cli.init();

Save the application:
Save this application as cliApp.js

Run the application:

node cliApp.js

Congratulations… your first CLI application in nodeJs has been successfully Created:

Output:

Thanks for reading.

--

--

Shubham Verma

A full-stack developer, In my free time, I write blogs and play guitar. I am both driven and self-motivated.