How to create a CLI with NodeJS

How to create a CLI with NodeJS:

 

Build A CLI With NodeJs

Hey there. In this tutorial, I am going to show you how to build a CLI app using NodeJS. This is going to be a simple app that will print a greeting to user, provided his/her name.

What is a CLI

CLI stands for Command Line Interface. This is the kind of interface where a user makes use of commands in a terminal/console/shell in order to carry out tasks.

Let’s start

First things first, let’s create a new directory to contain our app source code.
We are going to name that directory greet.

mkdir greet

Next thing is to move to that directory and initialise a new node project.

npm init

Running the above command to create a new node project is going to ask you some questions, you can choose to skip all of them by continually pressing the enter key.

Note that whatever you do, the name you choosed when asked the questions should match the name you want for your app.

Next things is to actually write the code for the app.
Open index.js (or whatever name you gave to the main file) and add the following code at the beginning.

#!/usr/bin/env node

// ...your code

You might have seen such code somewhere, especially if you have used python before. That line of code is called a shebang. What it does is : it makes your program executable.

But how does a shebang work ?

It is a program loader, which will essentially look for an interpreter for the kind of instructions the program contains and run it, passing as first argument the path to the main file.
In this case, it will look for node executable in usr/bin and run it, passing the path to your main javascript file as first argument.

Next comes our main program. Our program needs to take the name of the user as first argument. Luckily, Nodejs makes it easy to access command line arguments. This arguments are accessed through process.argv.
Add the following to your code :

console.log(process.argv);

Now try running your program. You will notice the following output :

[
  '/data/data/com.termux/files/usr/bin/node',
  '/data/data/com.termux/files/home/greet/index.js'
]

We are not adding any arguments to our node programs but we get two. By default, Nodejs will pass two arguments to you program, regardless if it has to take any. The first is the absolute path to the Nodejs executable and the second is the absolute path to your file. 
Now try running your program again, passing anything as argument. Try

node index.js hello

You will get the following

[
  '/data/data/com.termux/files/usr/bin/node',
  '/data/data/com.termux/files/home/greet/index.js',
  'hello'
]

So our argument comes after the first two. We therefore need to slice those two first away from the array to get a new array containing only our arguments.

const args = process.argv.slice(2)

Your code should look like this now

#!/usr/bin/env node

const args = process.argv.slice(2)

console.log(args)

Now try running your script passing it any two arguments. You will get back an array containing the arguments you passed.

Now we want to access the first argument as the name of the user to greet. That should be the first element of the arguments array.
You will end up with such code :

#!/usr/bin/env node

const args = process.argv.slice(2)

console.log(`Hello ${args[0]}`)

On the last line we are sending a Hello message + the first argument we get which should be the name of the user.

Time to turn it into a CLI

Now we want to turn the app into a CLI that we can use anywhere in our terminal. 
Follow the below steps .
First add a bin key to your package.json and set it’s value to the name of your main script. Here is what mine looks like :

{
    "name": "greet",
    "version": "1.0.0",
    "description": "A simple cli to greet users",
    "main": "index.js",
    "bin": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\"
},
"author": "Josias Aurel",
"license": "MIT"
}

Now, in the root of your project, run

npm link

What this command does, is it creates a symlink i.e, links your script to a global executable, making your script available globally in your terminal.
Now you can use your CLI like you will use any other.
Try running

greet Mike

And you should get a greeting saying Hello Mike in your terminal. You are free to close your terminal or try it anywhere in it and it will work.

You have reached the end of this tutorial.

from Tumblr https://generouspiratequeen.tumblr.com/post/636830989086294016

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s