DEV Community

Cover image for Create your First CLI App
Kaustubh Manglurkar
Kaustubh Manglurkar

Posted on • Updated on

Create your First CLI App

In this blog, we would learn to create a very basic CLI (Command Line Interface) app using JavaScript and NodeJS. We would also be understanding concepts such as objects, arrays, and functions in JavaScript.

A brief about what we're building

We're going to create a CLI quiz app on the Netflix original series, Stranger Things. As the app is going to be interactive, we'll first start by learning to take an input from the user. We'll then ask questions one by one for which the user would have to type in their answers. To store these questions and their answers in our code, we would learn to implement some of the most important data structures like objects and arrays. At the end of the quiz, the users would see how much they have scored and can share it with everyone.

So fasten your seat belts, the ride is about to begin!

Alt Text

Setting up your dev environment

To create our CLI app, we'll be using repl.it to run our programs. Repl.it is a free IDE (integrated development environment) where one can write their programs in N number of languages. You would need to sign in and then click on 'Create new repl'. Once you've done that, click on Node.js and name your reply as 'first-cli-app' and then click on Create repl as shown below.

image

How to show output in your CLI app

In order to show your output in the CLI app, we use the 'console.log()' function. We pass our output through a string in JavaScript which is represented by "". For example, if I want to print my name, I would write: console.log("Kaustubh"); in the code editor and click on 'Run'. The output would be shown the console as follows:
image

Learning to read user input

To take input in a CLI app, we need an npm package called 'readline-sync'. In order to use this package in our code, we need to first install it. And we do that by typing -> var readlineSync = require('readline-sync');
You could just copy it from the npm package, but the more you type out code the better you'll get at it. Once you type the above and click on 'Run', the npm package gets installed in your CLI app.

Now, as every user who would take up this quiz will have a unique name, we store their names in a variable called userName. Please note: to name a variable in JS, the first letter of the first word is always small and the consequent words would have the first letter as capital.

When someone takes this quiz, we would first want to know their name so that we can display a welcome message. Type as following:

image

Once you've done this, it would ask the user for it's name as seen on the console.

Now, we want to welcome the user to this quiz. For doing so, we do exactly what we did earlier to show output using console.log(). Type as following:

image

Now, we have added multiple strings in the same function. And we do that by using '+'. We took user input and put that variable name in our console.log() function. Adding one string on the back of another string is called as 'string concatenation'. It basically means that we're merging multiple strings in the same function.

Till now, we've learnt to take input from the user and display the output. And that's what most programs do, the three building blocks of any program are: input -> processing -> output.

Also, as a best practice - it's good to use a ';' (semicolon) after every line of code as the compiler uses it to differentiate between different statements. Your code would still work if you didn't use one.

Functions in JavaScript

A function is just a piece of information that can be called and used repeatedly in your program. As this is going to be a 'question, answer' quiz - we write a function as follows:

image

A few things to understand here: 'play' is the name of the function, (question, answer) are the function parameters that we've defined, and inside {} we write code for what needs to be done when the function 'play()' is called anywhere in the program.

Now, inside the function we need to put some conditions that would tell the user whether the answer they've entered for a particular question is correct or not. Based on that, we then increment or decrement their scores. To do this, we need to first understand the 'if-else' statement in JavaScript which is called as 'branching'.

Branching in JavaScript

Now, we first need to take userAnswer as an input, and we do that using what we did to take user's name using readline-sync as follows:
image

Now, you would see that we don't put the question explicitly in readlineSync.question(). Instead, we use the 'question' parameter that we defined in our 'play' function. The exact question, answer would be passed as an argument to the function when we call it later in our code. This might seem a bit overwhelming, but you'll get a hang of it as we proceed. Just don't give up!
You must be wondering, what are arguments? Arguments are basically the values that are passed to the function when it is called.

Coming back to our code block inside the play function. Now once the user has entered an answer to a particular question, we would want to check whether it's correct or not and then display that on the screen accordingly. We do that as follows:

image

A few things to understand here. '===' is used for comparing and checking whether two values are same or not, and that's what we want to do -- we want to see whether the userAnswer is the same as the actual answer. '=' in JS is used for assigning a particular value to a variable. Now, if the userAnswer is correct, we print it using console.log(). And we also want to increment their score, hence we write -> score = score + 1;
As score is a variable, we initialize it with a value and hence we write -> var score = 0;

We're now done with defining the function, and would proceed to call our play function with explicit 'question, answer' values to see whether our game works or not.

Calling the play function

Now we call the play function here, and pass the arguments which are real values.
image

And this how the game would appear when we run it:
image

Similarly, we can call the play function as many times as we want and pass different arguments every time. We can also print the user score in the end as follows:
image

The Output or the game would appear as follows:
image

We use '\n' whenever we want the output of that particular line of code to appear on a new line.

One thing you must've now realized is that if you write the answer in lowercase, it shows 'you are wrong' as the output. In order to tackle that, explore this and find out how to use it in your code. I'm sure you would be able to do it!

Now, we've finally created a very basic version of a CLI app. Congratulations, if you made it till here!

However, this is not the most efficient way of creating a CLI app. We would now have to step-up and learn some basic and the most important data structures that we're going to cover next!

Introduction to Data structures

What is a data structure?

A data structure is just a way of organizing data in a particular fashion. However, it's very important to understand which data structure needs to be used where. In the context of this app, we would only need to know what are arrays and what are objects. So let's get started with understanding an array.

Arrays in JavaScript

Whenever we want a list in a program, the most basic data structure to go to is an array. Let's see how an array of items looks like:
image

We create an array called shoppingList and list four items in it. Now, in order to access the elements of the array - we write:

image

When we type the above, we get 'milk' as the output in our console. '[ ]' is used for putting in the item position that we want to access. Items in a list are arranged sequentially in the form of index numbers which starts from '0'. Hence, in order to access the second element from the array, we write -> console.log(shoppingList[1]);

Now, every array has some properties and one of those is the '.length' property. We can find the length of an array by doing the following:

image

We assign a variable to the length of the array and the value gets stored in that variable. We then go on to print that variable to display the length. Please note: you can have any variable name of your choice.

Now let's say, we want to print every item in the list. In order to do that, we need to understand the 'for' loop.

Understanding the 'for' loop

A 'for' loop is used when we want to print a list or anything in our program repeatedly. Now, let's understand its syntax:

image

The three conditions mentioned above need to separated by a ';' (semicolon). Let's execute a simple program using the for loop. Let's say, we want to print 'Batman' five times. To do that, we use the for loop as follows:
image

We get the following as the output:
image

Let's understand how it executes. The var 'i' takes an initial value zero, checks the exit condition (basically when the loop should stop executing) and then runs the block of code which prints the output. After that, the var 'i' gets incremented by 1, and it again checks the exit condition. This goes on until 'i' takes the value 5 which does not satisfy the exit condition, and that's where the loop gets terminated.

Thus, we can now print every item in our shoppingList by using the for loop. Now, we move on to our next data structure which is an 'Object'.

Objects in JavaScript

Objects are data structures that act like a database where you can store information and access that information or value based on a 'key'. An object is like the index page of any book, wherein you know how to find something based on the page number, where page number is the 'key' and the information that you want to access is the 'value'.

In the context of this app, we would be using an object to store our questions and their respective answers. The syntax of an object is as follows:
image

An object can have multiples 'key-value' pairs. Let's understand that by taking an example:
image

As we can see, an object (superman in this case) can have various attributes such as strength, power, etc. which are the 'keys' here. Hence, in order to access the value - we need to know the key of that value. Let's say we want to access superman's power, then we type the following:
image

And we get 'flight' as the output on our console. Please note, the 'key-value' pairs in an object need to be separated by a ',' (comma).

We've now understood how to work with arrays and objects. Let's club this all together to create our final project which is the 'Stranger Things quiz app.'

Season Finale

Now, everything remains the same till we declared our play function above. You can remove the multiple play function calls that we did above, and let's get started.

So first, we need to store all our questions and answers in an object. We do that as follows:
image

Now, we need to go through the database one by one and for doing that we need to put that in a list (an array). We'll then run a for loop which would go through all the questions sequentially.

image

In the for loop, we don't directly put the value 5 instead we use the '.length' property that we learnt so that we don't have to worry about changing the exit condition time and again if the number of questions are increased or decreased as the '.length' property would take care of it.

As the 'for' loop goes through one question at a time, we store the currentQuestion in a variable based on the index value (questions[i]) and then call the 'play' function that we defined initially along with the key values (.question, .answer) for each question in our object.

To go a bit advanced, you can write the object directly into the array as follows:

image

This might seem a bit overwhelming and it's totally alright as everyone takes time to understand data structures. So just read through it all again, and try doing every bit by yourself.

We can finally, print the scores to show the user how many questions they got correct.

And with that, we've come to the end our CLI app. Kudos to you if you tried doing each and everything step-by-step. As a best practice, it would be good to do it all from scratch by yourself to see how much you really understood and remember.

For sharing the app with your friends and family so that they can try out the quiz, type the following at the end of your repl URL without any space -> ?embed=1&output=1

Bonus

Create a database to store a few highscores, and at the end of the game you can show it to the users. If they beat the highscore, ask them to send you a screen grab so that you can update your database with their name.

It shouldn't be very difficult to do it if you've understood objects, arrays, and the for loop.

Here's the entire CLI quiz app that you can try out and here's the source, you would find that I've used some other packages as well like the chalk for styling purposes which you can explore by yourself.

Tip

As a user, you would agree that we hate to type a lot and that's the case with CLI apps. We need to make sure that the user has to type as less as possible to get something done. Hence, instead of having the user type the entire answer, you can give them some options to choose from. Try playing this quiz to know more about me where I've enabled the MCQ feature, and here's the source for the same.

Let me know if you guys liked the blog and please share your thoughts or any questions in the comments below.

I'll be back soon with another interesting topic area, until then - keep learning, keep sharing!

Top comments (0)