A beginner’s guide for creating Command Line programs in Node.js

michael sorensen
4 min readMay 29, 2019

--

Objective: This guide will teach you how to write a program that accepts command line arguments using Node.js.
Audience: People who have never written a single Node.js program but, are somewhat familiar with the terminal and have some basic programming knowledge.

Step 0: Setup
Most guides like these already have environment setup instructions so I won’t dive too deep here but, for the uninitiated here is a summary of the steps you should take and a few relevant links:
1. Install node.js

2. Ready a terminal (powershell, gitbash, mac terminal, etc)

3. Verify that node.js is installed by opening a terminal and typing node -v in the terminal(this guide was written using v10.13.0)

4. Ready a favorite text editor (I prefer Visual Studio Code)

Step 1: Console Logging and Hello World
Yep, it’s another hello world application. You already know what to expect so let’s get right into it.

  1. Create a new file named hello-world.js (for those terminal enthusiasts just type touch hello-world.js)
  2. Open that file with your favorite text editor and type console.log("hello world!"); on the first line. To those new to javascript, console.log prints whatever string you pass as an argument similar to python’s print function. Go ahead and save that file.
  3. Open or go back to your terminal and change your directory (cd) to where you saved that javascript file we just created. Inside the terminal type node hello-world (note that the .js file ending is not strictly necessary). You should see the output hello world! in your terminal. Congratulations you just created and executed your first Node.js program.

Step 2: Process.argv and accepting user input
Alright so we know how to run a node.js program but logging to the console is not terribly useful. We do know that most command line tools accept some form of input (ex. cd <some location>). How do we do that in Node.js?

Node.js exposes a global variable called Process that we can use to grab information from the user. Now let’s see exactly how we can do that.

  1. Create a new file called hello.js
  2. Open that file and insert the following snippet and save the file.
const name = process.argv[2];console.log("hello " + name);

In short, we are storing a user submitted value into a constant variable we call name then we are logging it into the console. There are a couple things which I encourage you to go mull over like the const keyword and string concatenation but, those are beyond the scope of this guide.

3. Run the program by typing node hello samantha wherever you saved the file. You should find that the program responds with hello samantha . You should then repeat this using a different name to confirm that it is capturing user input. Neat!

Step 3. Process.argv continued…
Okay there’s a lot to unpack with process.argv but, in an attempt to sum it up it is an array of values corresponding to the values entered in the command.

For example; the last program we ran was node hello samantha if you console.log(process.argv) you should see values like this:

[ '/your/nodejs/installation/path', '/the/path/to/your/hello.js', 'samantha']

You can include virtually as many command line arguments as you need thanks to this feature.

Step 4. adding functionality
To finish off this guide I want to leave you with the ability to read more in-depth node.js guides from any time period. With that let’s write a program that manipulates some of the values the user provides.

  1. Create a new file called add.js
  2. Open that file in your text editor and add code that accepts 2 values and stores those values into variables.
const num1 = process.argv[2];const num2 = process.argv[3];

3. Include a function that adds those values together

function add(param_num1, param_num2) {    return param_num1 + param_num2;}

4. Call that function and store the result in a variable called sum

const sum = add(num1, num2);

5. Log sum to the console

console.log(`sum: ${sum}`);

Now if you run the program by typing the following into your terminal: node add 2 2 you might be surprised to see the number 22 appear on your screen. That is because Node.js can only interpret user input as a string data type. Data types in javascript can be a little tricky if coming from a more strictly typed language so I highly suggest reviewing W3Schools article on the subject.

To resolve this issue we can change parse the values to be numbers like

const num1 = parseInt(process.argv[2]);const num2 = parseInt(process.argv[3]);

So if we run the program we should see the expected output of 4 .

**A note on functions**
Functions can take many different shapes in javascript and there are many ways to declare them. For experienced developers the differences are important but, for beginners the end result is mostly the same.

  • function(){ //some logic } is an anonymous function
  • function myFunction(){ //some logic } is a named function
  • const myFunction = function(){ // some logic } is also a named function
  • const myArrowFunction = () => { // some logic } is a named arrow function

You may see functions appear in different forms on your journey to learn Node.js and javascript. Javascript has been changing since its inception and will likely continue to while old guides will still be out there on the internet. Hopefully this information will shed some additional insight into what otherwise might be a confusing read.

Github Repository: https://github.com/Mikkal24/tutorials/tree/master/cli-part1

--

--