Step-By-Step Guide To Build CLI Applications With Node.js

By Mohit Surati Node.js 90 Views

CLI applications have a significant advantage over GUI by providing ease of working and excellent productivity to programmers and system administrators.

CLI is a text-based user interface that allows you to manage your computer task by just writing one-line commands and responding to the text-based user interface.

With the help of the command-line interface, you can quickly execute a batch processing task without any mistake or beaches.

Compared to the graphical user interface, the command line interface is more comfortable to streamline and automate all the monotonous tasks.

Moreover, the graphical user interface also requires comparatively higher computation and hardware support.

You must be also comfortable with the layout of the GUI to use it properly. However, when it comes to CLI, all you need a one-line code and everything will be taken care of.

However, building a command-line interface is not an easy task. Unless you have good coding knowledge about JavaScript frameworks like Node.js, MongoDB, Angular, etc. you won’t be able to create an interactive command-line interface of your choice so easily.

But thanks to user-friendly JavaScript Framework like Node.js, you can create a customized command-line interface of your choice by just writing intuitive and straightforward code.

Why Use Node.js?

Node.js is one of the most scalable JavaScript frameworks that can improve the scalability of your projects.

Even though you want to expand your application horizontally or vertically, Node.js would help you do that effortlessly.

Why Choose Node.js

Node.js is comparatively easier to learn since most of the web developers are acquainted with JavaScript, so to integrate and start developing Node.js code becomes extremely easy for most of the web developers.

Node.js is a full-stack platform where you can code for both front-end and back-end of your application.

If you are going for other platforms, you might have to go for other frameworks for either of the sides of your app, except for Node.js.

Read on to know more about how with the help of Node.js, Node JS Development Company can create the magic of building your command-line interface.

In our example, today, we will use the windows system and use Yarn as our package manager.

So, let’s dive right in!

Step 1: Install Node.js

Before start building our command-line interface with the help of Node.js, you will need the platform, Node.js,  installed in your system to be able to write code that works.

Now, download the respective Node.js installer in your system. Node is supported on both the devices Mac and Windows so that you can find your respective files on the official website of Node.js.

Download NodeJS

Once the download is complete, you can begin the installation process. You will have all the necessary details that you need to follow once you begin the installation.

After you install the Node.js, you can restart your system to ensure that it works.

After restarting, open a command prompt in your Windows system and type node -v to know the version of the Node.js platform installed on your system.

If you have followed all the steps correctly, you will see the Node.js version.

To develop your command-line interface using Node.js, you will need to set up an environment where you can write your code is comprehensible by the system. You can do so with the help of packages.

Before diving deep into writing the JavaScript code, let’s understand the package manager that we are going to use for tasks.

Step 2: Installing Yarn

Node.js has a primary package manager named npm, which you can also use to build your CLI using this JavaScript framework. However, I am more comfortable with another package known as Yarn.

As my personal opinion, Yarn replaces all the necessary features and workflow that npm provides and also add more efficiency and debug code more quickly.

Based on your system support, you need to install some files to utilize Yarn for this project.

If you are using macOS, you don’t have to go for any further installation as Yarn demands only homebrew which is pre-installed in the system.

Just write the below code in your CLI of macOS to install Yarn.

brew install node yarn

If you are using Windows, follow the procedure below, download the latest installer of Yarn, and you will be provided with the further steps to install it on your windows.

Step 3: Create Your Repository

As soon as you get all the ingredients, it is time to start mixing them to create a delicious cake.

No, have not come to another blog article here. As you download and install Node.js and Yarn, you can then start writing and executing code to build an interactive command-line interface.

But to build any application on Node.js, the first step is to create a repository. So, write the below code to develop your first repository.

mkdir my-cli

cd my-cli

yarn init # As soon as you write the code, you might have to answer a few questions

yarn add commander shelljs

yarn add -D pkg

Now, go to your index.js file and edit the code below to make everything quicker for future tasks.

// index.js

/**

* This is the common way to import a package in NodeJS.

* The CommonJS module system is used.

*/

const customcli = require('commander')

/**

* () => {} is an arrow function, which belongs to the ES6 (ESMAScript 6) standard.

*/

customcli.action(() => {

console.log(‘Hello Programmer!') // This line will print “Hello Programmer!” on the screen.

})

/**

* This line is mandatory for the code to successfully run.

*/

customcli.parse(process.argv)

Now, check whether the code is placed correctly and working or not by trying below lines of code in your command-line interface. The string mentioned along with #=> sign is the output that you will get and verification that your code is working properly.

node index.js

#=> Hello Programmer!
node index.js hello

#=> Hello Programmer!

In the code snippet written above, it does two things. It shows what will be executed as soon as the command is triggered. Then, it also calls progress.argv which triggers control to print something on the screen.

Step 4: Provide More Options

In this particular segment, the real magic happens. We are going to write a code where we can provide some options that offer custom output.

There is also a provision for using Docker in Node.js Development. So, explore that aspect.

Beside simple Hello world and demo code, there are a lot of interactive things that you can do with Node.js and Yarn.

So far, we have developed a basic code that prints some static message on the screen. Now, we will make the code comprehend and print dynamic output provided by the user.

In your index.js file, type below the line of codes to make your CLI dynamic.

// index.js

/**

* This is the common way to import a package in NodeJS.

* The CommonJS module system is used.

*/

const customcli = require('commander')

/**

* This section is used to showcase the responses of our bot.

* @param {string} word The intended output

*/

const bot = word => {

console.log(Hey, the bot says:', word)

}

/**

* This section will have an array where the values will be recorded.

* @param {string} val The fresh value pushed in the array

* @param {array} arr The original array

* @return {array} New array

*/

const collect = (val, arr) => {

arr.push(val)

return arr

}

customcli

.option('-u, --username <name>', `specify the user's name`)

.option('-a, --age [age]', `specify the user's age`)

.option(

'-g, --gender [gender]',

`specify the user's gender`,

/^(male|female)$/i,

'private',

)

.option('-i, --additional-info [info]', 'additional information', collect, [])

.option('-s, --silent', 'disable output')

.option('--no-gender-output', 'disable gender output')

.action(() => {

if (!customcli.silent) {

/**

* `...` is called a template string (aka template literal). Expressions can be evaluated in a

* template string, by using ${}, which is very similar to what we do in the command line with shell

* scripts.

* In this example, we are using Node.js’ function typeof to determine the type of variable.

* We also use ternary operator instead of if ... else ... for simplicity.

*/

const nameLine = `Hello ${

typeof customcli.username === 'string' ? customcli.username : 'world'

}`

bot(nameLine)

const ageLine =

typeof customcli.age === 'string'

? `I know you are ${customcli.age}`

: 'I do not know your age'

bot(ageLine)

/**

* Here we combine use of arrow function and IIFE (Immediately Invoked Function Expression).

*/

if (customcli.genderOutput) {

const genderLine = (() => {

switch (customcli.gender) {

case 'male':

return 'You are a man'

case 'female':

return 'You are a woman'

default:

return 'You haven’t mentioned any gender'

}

})()

bot(genderLine)

}

/**

* Array.forEach is an easy way to perform iterative execution to all elements in an array.

*/

customcli.additionalInfo.forEach(info => {

const infoLine = `I also know ${info}`

bot(infoLine)

})

}

})

/**

* This line is necessary for the command to take effect.

*/

customcli.parse(process.argv)

Now, this code might seem overwhelming to the people who are not acquainted with the Node.js framework.

To sum up, the long snippet mentioned above records the inputs that you have provided and ensure the correct display of the output screen.

In this example, we have mentioned a conversation between a user and the bot.

So, you need to write below code.

node index.js -u Vicky -a 25 -g Female -i "Social Media is a great platform to expand a small business."

Then, you should see output like below.

The bot says: Hello Vicky // (name)

The bot says: I know you are 25 // (age)

The bot says: You are a Female // (gender)

The bot says: I also know Social Media is a great platform to expand a small business. // (additionalInfo)

This is the beauty of coding in Node.js.

In the above example, if you don’t mention your name, it will be printed as “Hello world

If you don’t enter your age, you will get a message like, “I don’t know your age.

And, if you don’t mention your gender, the bot will say ‘You haven’t mentioned any gender

Read also: Why Should You Opt for Node.js Framework in Web App Development?

Step 5: Adding Sub-Commands

With the help of some commands, you can make your command-line interface more interactive and engaging.

Now, we will add time, sum, and match commands.

Let’s edit the index.js file once again.

// index.js

// ...

customcli

.command('time')

.alias('t')

.description('show the current local time')

.action(() => {

/**

* The `Date.now()` method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

* By using `new Date()`, a Date object is created.

* The `.toLocaleTimeString()` method then transforms it into the human readable form.

*/

const now = new Date(Date.now())

console.log(now.toLocaleTimeString())

})

customcli

.command('sum')

.alias('s')

.arguments('<numbers...>')

.description('calculate sum of several numbers')

.action(numbers => {

/**

* `Array.prototype.reduce()` executes the reducer function on each member of the array,

* resulting in a single output value.

*/

console.log(

numbers.reduce(

(accumulator, currentValue) =>

parseFloat(accumulator) + parseFloat(currentValue),

),

)

})

customcli

.command('match')

.alias('m')

.arguments('<first> <second> [coefficient]')

.option('-r, --random', 'add a random value to the final result')

.description('calculate how much the first person matches the second one')

.action((first, second, coefficient = 1, cmd) => {

let result = Math.abs(first.length - second.length)

if (cmd.random) {

result += Math.random()

}

result *= coefficient

console.log(`The match point of ${first} and ${second} is ${result}`)

})

/**

* This line is necessary for the command to take effect.

*/

customcli.parse(process.argv)

.command() specifies the name of the sub-command
.alias() specifies the alias of the sub-command
.arguments() specifies the arguments the sub-command will accept

The time command requires no arguments at all. So, we just write.

node index.js time

And you will get the current time as the output.

You can also calculate the summation of the series of the numbers. Here, you will need more than one argument for your sum command to calculate the total of the numbers.

So, we will write,

node index.js sum 4 2 5 6.2

The result will be

17.2

Step 6: Leverage ShellJS

If you want to avoid batch processing your outputs, you should download ShellJS in your Node.js system. ShellJS is the portable implementation of Unix shell commands on top of Node.js. You can use it to eliminate the shell script’s dependency.

To be able to use ShellJS in your Node.js application, edit your index.js source file and add the code snippet below.

// index.js

const customcli = require('commander')

const shelljs = require('shelljs')

// ...

customcli

.command('shell')

.description('use shelljs to do some shell work')

.action(() => {

shelljs.ls('-Al').forEach(file => {

const birthTimeUTC = new Date(file.birthtimeMs).toUTCString()

console.log(`${file.name} was created at ${birthTimeUTC}.`)

})

})

/**

* This line is necessary for the command to take effect.

*/

customcli.parse(process.argv)

This way, you can creatively use ShellJS in your CLI. You can try using the commands mentioned in this source of ShellJS.

Step 7: Format Your Code

Formatting is extremely important for your source code to be comprehensive and readable. That’s where choosing the right Node.js Frameworks Of 2019 became essential.

Understand that your source code might be used and utilized by many people. Unless your snippets are thoroughly manipulated by you only, you can keep it as it is nobody is going to work with it.

However, if you are working for the client project or having a team of talented Node.js developers, you need to ensure that your source code is comprehensive enough to be understood by others.

This way, even if your role in the project upgrades, you can assign or explain your code to others effectively if you have formatted the code.

To start formatting your code in Node.js, you can club the declarative statements followed by all the defining statements. Then, you can write the code about the process.argv at the end of the snippet.

Step 8: Packaging Your Code

Packaging the Node.js code is equal to grouping all the library files and source code and make it a single source file that could be utilized in other projects.

All you need to do is open this packaged resource file in your other Node.js source code so that all methods and classes don’t require to be defined again. They can be just called and executed in the project.

In our example, we try to provide a command-line interface to all the Node.js developers and users by packaging source code into a single file.

In this step, we are going to use pkg, which will help us to transform our source file into an executable binary file.

The most exciting and somewhat magical thing about the binary file is its independence from Node.js platform.

Yes, the binary file can be utilized in other projects and source code irrespective of their platforms and formats.

To ensure that the name of the output matches with our file name, we will rename the index.js file into customcli.js.

So, we need to make some changes in our package.json file.

"scripts": {

"package:mac": "pkg customcli.js --targets node10-macos-x64 --output dist/mac/customcli",

"package:win": "pkg customcli.js --targets node10-win-x64 --output dist/win/customcli.exe",

"package:linux": "pkg customcli.js --targets node10-linux-x64 --output dist/linux/customcli",

"package:all": "yarn package:mac && yarn package:win && yarn package:linux"

}

Conclusion

Developing a command-line interface requires a little bit of knowledge and planning to come up with the most interactive and useful CLI to streamline your tasks.

Today, we have developed the basic CLI using Node.js framework.

We hope you had a great time reading this article and it helps you to become aware of this important thing about Node.js framework. Thank You.!

Disclaimer: We at eSparkBiz Technologies have created this blog with all the consideration and utmost care. We always strive for excellence in each of our blog posts and for that purpose, we ensure that all the information written in the blog is complete, correct, comprehensible, accurate and up-to-date. However, we can’t always guarantee that the information written in the blog correct, accurate or up-to-date. Therefore, we always advise our valuable readers not to take any kind of decisions based on the information as well as the views shared by our authors. The readers should always conduct an in-depth research before making the final decision. In addition to these, all the logos, 3rd part trademarks and screenshots of websites & mobile apps are the property of the individual owners. We’re not associated with any of them.

Mohit Surati

Mohit Surati

A post-graduate in Computer Engineering. Passionate about innovative writing & Content Marketing. A rich vein of experience in writing articles related to WordPress right from plugins, themes, customization, security, WooCommerce & Gutenberg. Pens down his thoughts for eSparkBiz @Custom WordPress Development Company where you can Hire WordPress Developer as per your requirements.

Search

Follow us

Subscribe Newsletter

Call us Today

telephone

Got any Questions?
call us Today!

+1 408 850 1488 [email protected]

Related Post

Best Practices To Develop a World-Class Node.js App

Best Practices To Develop a World-Class Node.js App

Node.js is one of the most popular and renowned JavaScript frameworks that support frontend and backend development of a web application. People nowadays are searching…

How To Build Microservice Architecture With Node.js?

How To Build Microservice Architecture With Node.js?

What if I tell you that you can develop the most scalable application out there while ensuring most efficiency and customer satisfaction rate at the…

How to Use Docker for Node.js Development?

How to Use Docker for Node.js Development?

2013 saw the advent of Docker in the tech and development world. Since then, Docker has now managed to become the hottest trend as far…