How JavaScript Works: Why you need a CLI and How to build a CLI with JavaScript

Ukpai Ugochi
SessionStack Blog
Published in
8 min readJul 19, 2022

This is post # 68 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building SessionStack, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.

Introduction

A command-line interface (CLI) is a tool that accepts text as input from users. These text inputs are commands from the user that are executed by the computer. In the early days before the invention of the mouse, CLI was used for entering the necessary computer commands.

However, the usage of the CLI has evolved. For instance, operating systems (OS) implement a command-line interface in a shell to allow the execution of administrative tasks. Although the advent of a graphical user interface (GUI) may seem like an alternative to a command-line interface, CLIs are still widely used. For example, most administrative tasks, installation, and access features that aren’t on the GUI need a CLI interaction.

This article will explore CLI, its evolution, uses, and how to create an interactive Command-Line Interface with Node.js.

What is a CLI, the evolution of CLI

CLI is a text-based program that enables users to instruct computers with text commands. It is used for running programs, managing computer files, and also interacting with computers. CLI accepts text inputs as commands and runs these commands to execute specific tasks.

And to interact with an operating system using the command-line interface, you need to use a shell. A shell is a program that provides access to operating system components. There are two types of shell in modern-day operating systems: the CLI shell, which enables users to interact with the OS (Operating System) using commands, and the Graphical User Interface (GUI) shell, which enables users to interact with the OS using a graphical interface.

In the early 1960s — — before the introduction of the computer mouse, the only way of communicating with a computer was through computer terminals. And these commands were passed to the computer from the keyboard through the Command-Line interface. In the 1970s, the Unix shell and Bourne shell were introduced. Below are some CLI operations specific to three major operating systems:

Linux CLI Commands

MacOS Terminal commands

Windows CLI commands

Why You need a CLI

In the last section, we’ve explored the evolution of CLIs. However, one question we are yet to answer is why we need a CLI in a modern world of computers like ours, where we have the GUI. Here are a few reasons you need a CLI.

  1. GUI may not have the same flexibility as a command-line interface. For example, GUIs do not support scripting and automation. Navigating through files and folders may require numerous clicks and dialog boxes, while you can accomplish the same function with just one command line.
  2. The CLI is still widely used, especially by software developers and system administrators for the configuration of computers. For example, package managers like npm only support CLI. And some installations can only be done from the CLI.
  3. CLI makes system management and configuration easier as a simple CLI command can quickly adjust configurations for a large group of systems at once
  4. Basic knowledge of CLI commands can enable troubleshooting of network connection issues.

How to Create a CLI with Node.js

Node.js is a back-end JavaScript runtime that executes JavaScript code outside a web browser. It allows developers to write CLI tools for server-side scripting. We are using Node.js because of its ecosystem support and vast libraries that we can have access to with npm.

In this section, we’ll explore CLI creation with Node.js. We’ll create a tool that helps engineers translate texts into their native language. Consequently, we eliminate the clicks and hassle required in configuring a translator via a GUI. And to do this, we need to set up our working environment. Let’s do this in the next sub-section.

Installation and Setup

To create a CLI with Node.js, you need to install Node.js. Follow this guide to download and install Node.js in your local environment. We will also need a text editor to write our codes.

Next, run the command below to create an application folder for our translator project.

mkdir translator-cli

Now, navigate to the project’s directory.

cd translator-cli

Initialize the project by using NPM by running:

npm init

You will be asked some questions like the name of your package etc. Fill in the appropriate information. And note that a package.json file has been generated.

Now, let’s write the logic of our CLI.

Writing logic

The bin folder is where the executable files of our package are located. So we will create a bin folder for our translator. And this folder will contain the entry point of our application, app.js.

Now, create a bin folder at the root of your project. In the folder, create an app.js file. Open the package.json file in your editor, and replace the main part with bin/app.js.

This setup will let Node.js know that the entry point of our project is app.js.

Next, we’ll create a keyword for calling our CLI. And to do this, add the following entry to our package.json file.

The translator-cli property is the keyword users will use for calling our CLI while the value ./bin/app.js points the keyword to our entry point file that would hold our CLI logic.

Add the following lines to the app.js file in the bin folder.

The first line of the code above is an instance of the shebang line. And this is the first line in an executable plain-text file on Unix-like platforms. It tells the system what interpreter to pass that file to for execution. We’re also telling our package to print translator-cli in the console when we run the translator-cli keyword.

However, if we try to run our project by executing our entry file with node ./bin/app.js, you will realize the text translator-cli is very plain.

We can beautify this by using the figlet library. And to install figlet run the command below:

npm install figlet

Now import the figlet library into our package by adding the line below at the top of your app.js file.

const figlet = require(“figlet”);

And replace the console.log part of the app.js file with the code below:

Notice that when you run the package, the printed CLI response is prettier.

Command-line arguments

Although we have the basic part of a CLI, what is a CLI without the ability to manage arguments? In this section, we will fully implement our translator tool. Node.js has some libraries such as commander and yargs that enable the proper management of command-line arguments.

To install commander run the command below:

npm i commander

Next, we’ll import and configure the commander library as seen below:

Next, we will install the vitalets/google-translate-api package via npm by running:

npm install @vitalets/google-translate-api

The vitalets/google-translate-api NPM package, translate sentences with the translate function. And the translate function takes two arguments:

  1. The sentence to translate — — as a string
  2. An options object containing properties such as from and to. The value of these properties represents the language we are translating from and the language we are translating to.

For example, we can translate a sentence from French to English with the example below.

However, this library offers automatic language detection, so we’ll leverage that. Therefore, instead of specifying a from and to language, we’ll only provide the to language, and vitalets/google-translate-api will detect our from language.

Now, import the vitalets/google-translate-api library into our CLI. And add the following code to your bin/app.js file.

const translate = require(‘@vitalets/google-translate-api’);

Next, we’ll add the .action method to our .bin/app file, under the // Help options section, and before the program.parse(); method.

Now, when the user runs the command below, they should get an output like the image below:

node ./bin/app.js translate en ‘Je parle Anglais’

Note the reason for the quote around the sentence is for our CLI to recognize Je parle Anglais as a sentence and not break it down as commands or options.

While this is a great example to illustrate the creation of a CLI with Node.js, we can make this better.

For instance, we can write precise error messages in a utility or helper file, to properly convey errors. And this is useful in our app because the vitalets/google-translate-api library only supports the iso of languages. Therefore, if I use French as the from language instead of fr, it’ll throw an error.

Another example is how the language only supports maximum text length for a single translation call as 5000 characters. So users have to split their sentences into multiple batches when they’re greater than 5000 characters. Therefore, we can add an error message or description explaining that the users can put in more than 5000 characters in a batch.

Conclusion

CLI or Command-Line Interface is an important tool for general users. And this is because it aids communication with the Operating System and carries out tasks quickly by passing commands. Although CLIs are important, it is not a bed of roses. For instance, it is not user-friendly and requires steeper learning curves too.

In this article, we talked about CLI and the history and evolution of CLI. We explored some CLI commands specific to certain OS.

Lastly, we got hands-on experience on how to create our own CLI project by building a project that helps in project bootstrapping and git initialization.

Even if you feel like the proper decisions have been made, it’s always necessary to verify that this is indeed true and your users have a great experience with your product.

A solution like SessionStack allows you to watch user sessions as videos, allowing you to see exactly what happened during their journey.

Combining this visual information with all of the tech data from the browser such as errors, stack traces, network issues, debug data, etc. you can easily understand problematic areas in your product and efficiently resolve them.

There is a free trial if you’d like to give SessionStack a try.

SessionStack replaying a session

Interested in more about JavaScript? Check out all “How JavaScript works” publications here.

--

--