How to create a CLI with NodeJS
Tags: node, cli, javascript
Published: 2020-12-06 14:15:59

# 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`. 
```shell
mkdir greet
```
Next thing is to move to that directory and initialise a new node project.
```shell
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.
```javascript
#!/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 :
```javascript
console.log(process.argv);
```
Now try running your program. You will notice the following output :
```shell
[
  '/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
```shell
node index.js hello
```
You will get the following
```shell
[
  '/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.
```javascript
const args = process.argv.slice(2)
```
Your code should look like this now
```javascript
#!/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 :
```javascript
#!/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 :
```javascript
{
    "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 
```shell
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
```shell
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.

Thank you for reading ♥️.
<a href="https://www.buymeacoffee.com/rocketstellar" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>