How to write and run your first application in Node.js

0 Shares
0
0
0
0

Introduction

Node.js is a popular open source runtime environment that can execute JavaScript outside of the browser using the V8 JavaScript engine, which is the same engine used to execute JavaScript in the Google Chrome web browser. The Node Runtime is commonly used to create command line tools and web servers.

Learning Node.js allows you to write your front-end and back-end code in the same language. Using JavaScript across the stack can help reduce context switching time, and libraries are more easily shared between your back-end server and front-end projects.

Also, thanks to its support for asynchronous execution, Node.js excels at I/O-intensive tasks, which makes it well-suited for the web. Real-time applications, such as video streaming or applications that constantly send and receive data, can run more efficiently when written in Node.js.

In this tutorial, you will create your first application with the Node.js runtime. You will learn about some specific Node concepts and work your way to creating an application that helps users check their system's environment variables. To do this, you will learn how to output strings to the console, receive input from the user, and access environment variables.

Prerequisites

To complete this tutorial, you will need:

  • Node.js is installed on your development machine. This tutorial uses Node.js version 10.16.0. To install it on macOS or Ubuntu 18.04, follow the steps in How to install Node.js and create a local development environment on macOS or the "Install using a PPA" section of How to install Node.js on Ubuntu 18.04.
  • Basic JavaScript knowledge you can find here: How to code in JavaScript.

Step 1 – Output to console

To write a “Hello, world!” program, open a command-line text editor like nano and create a new file:

nano hello.js

When the text editor opens, enter the following code:

console.log("Hello World");

The console object in Node.js provides simple methods for writing to stdout, stderr, or any other Node.js stream, which in most cases is the command line. The log method prints to the stdout stream, so you can see it in your console.

In the context of Node.js, streams are objects that can receive data, such as the stdout stream, or objects that can output data, such as a network socket or a file. In the case of stdout and stderr streams, any data sent to them is displayed in the console. One of the important things about streams is that they are easily redirected, so you can redirect the output of your program to a file, for example.

Save and exit nano by pressing CTRL+X, when prompted to save the file, press Y. Now your program is ready to run.

Step 2 – Run the program

To run this program, use the node command as follows:

node hello.js

The hello.js program runs and displays the following output:

Output
Hello World

The Node.js interpreter read the file and executed console.log (“Hello World”) by calling the log method of the global console object. The string “Hello World” was passed as an argument to the log function.

Although the quotation marks are necessary in the code to indicate that the text is a string, they are not printed on the screen.

Having confirmed that the program is working, let's make it more interactive.

Step 3 – Getting user input via command line arguments

Every time you run Node.js “Hello, World!” the program produces the same output. To make the program more dynamic, let’s take input from the user and display it on the screen.

Command line tools often accept various arguments that change their behavior. For example, running node with the –version argument will print the installed version instead of running the interpreter. At this point, you have accepted your code via command line arguments.

Create a new arguments.js file with nano:

nano arguments.js

Enter the following code:

console.log(process.argv);

The process object is a global Node.js object that contains functions and data that are all related to the running Node.js process. The argv property is an array of strings that contains all the command line arguments given to a program.

Save and exit nano by typing CTRL+X, press Y when prompted to save the file.

Now when you run this program, you provide a command line argument like this:

node arguments.js hello world

The output is as follows:

Output
[ '/usr/bin/node',
'/home/sammy/first-program/arguments.js',
'hello',
'world' ]

The first argument in the process.argv array is always the location of the Node.js binary that is running the program. The second argument is always the location of the file being executed. The remaining arguments are whatever the user entered, in this case: hello world.

We are more interested in the arguments that the user has entered, not the default arguments that Node.js provides. Open the arguments.js file for editing:

nano arguments.js

Change console.log(process.arg); to the following:

console.log(process.argv.slice(2));

Since argv is an array, you can use JavaScript's built-in slice method, which returns a collection of elements. When you pass the slice function with 2 as an argument, you get all the elements of argv after the second element. That is, the arguments that the user entered.

Run the program again with the node command and the same arguments as last time:

node arguments.js hello world

Now, the output is as follows:

Output
[ 'hello', 'world' ]

Now that you can collect input from the user, let's collect input from the application environment.

Step 4 – Accessing Environment Variables

Environment variables are key-value data stored outside of an application and provided by the operating system. They are typically set by the system or user and are available to all running processes for configuration or state purposes. You can access them using the Node process object.

Use nano to create a new environment file.

nano environment.js

Add the following code:

console.log(process.env);

The env object stores all the environment variables that are available when a Node.js application is running.

Save and exit as before and run the environment.js file with the node command.

node environment.js

After running the program, you should see output similar to the following:

Output
{ SHELL: '/bin/bash',
SESSION_MANAGER:
'local/digitalocean:@/tmp/.ICE-unix/1003,unix/digitalocean:/tmp/.ICE-unix/1003',
COLORTERM: 'truecolor',
SSH_AUTH_SOCK: '/run/user/1000/keyring/ssh',
XMODIFIERS: '@im=ibus',
DESKTOP_SESSION: 'ubuntu',
SSH_AGENT_PID: '1150',
PWD: '/home/sammy/first-program',
LOGNAME: 'sammy',
GPG_AGENT_INFO: '/run/user/1000/gnupg/S.gpg-agent:0:1',
GJS_DEBUG_TOPICS: 'JS ERROR;JS LOG',
WINDOWPATH: '2',
HOME: '/home/sammy',
USERNAME: 'sammy',
IM_CONFIG_PHASE: '2',
LANG: 'en_US.UTF-8',
VTE_VERSION: '5601',
CLUTTER_IM_MODULE: 'xim',
GJS_DEBUG_OUTPUT: 'stderr',
LESSCLOSE: '/usr/bin/lesspipe %s %s',
TERM: 'xterm-256color',
LESSOPEN: '| /usr/bin/lesspipe %s',
USER: 'sammy',
DISPLAY: ':0',
SHLVL: '1',
PATH:
'/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',
_: '/usr/bin/node',
OLDPWD: '/home/sammy' }

Keep in mind that many of the environment variables you see depend on your system configuration and settings, and your output may look significantly different than what you see here. Rather than viewing a long list of environment variables, you may want to retrieve a specific one.

Step 5 – Accessing a specific environment variable

In this step, you will view the environment variables and their values using the global process.env object and print their values to the console.

The process.env object is a simple mapping between environment variable names and their values, stored as strings. Like all objects in JavaScript, you access a property by referencing its name in parentheses.

Open the environment.js file for editing:

nano environment.js

Change console.log(process.env); to:

console.log(process.env["HOME"]);

Save the file and exit. Now run the environment.js application:

node environment.js

Now the output looks like this:

Output
/home/sammy

Instead of printing the entire object, you now print only the HOME property of process.env, which stores the value of the $HOME environment variable.

Again, keep in mind that the output of this code will likely be different from what you see here because it is specific to your system. Now that you can specify the environment variable to retrieve, you can enhance your application by asking the user for the variable they want to see.

Step 6 – Retrieve an argument in response to user input

Next, you will use the ability to read command line arguments and environment variables to create a command line tool that prints the value of an environment variable to the screen.

Use nano to create a new echo.js file:

nano echo.js

Add the following code:

const args = process.argv.slice(2);
console.log(process.env[args[0]]);

The first line of echo.js stores all the command line arguments that the user has provided in a constant variable called args. The second line prints the environment variable stored in the first element of args. That is, the first command line argument that the user has provided.

Save and exit nano, then run the program as follows:

node echo.js HOME

Now the output will be:

Output
/home/sammy

The HOME argument was stored in the args array, which was then used to find its value in the environment via the process.env object.

At this point you can now access the value of any environment variable on your system. To verify this, view the following variables: PWD, USER, PATH.

Retrieving individual variables is fine, but allowing the user to specify the number of variables they want is better.

Step 7 – View Multiple Environment Variables

Currently, the program can only check one environment variable at a time. It would be useful if we could accept multiple command line arguments and get their corresponding value in the environment. Use nano to edit echo.js:

nano echo.js

Edit the file so that it contains the following code instead:

const args = process.argv.slice(2);
args.forEach(arg => {
console.log(process.env[arg]);
});

The forEach method is a standard JavaScript method on all array objects. It accepts a callback function that is used when iterating over each element of the array. You use forEach on the args array and provide a callback function that prints the value of the current argument to the environment.

Save and exit the file. Now run the program again with two arguments:

node echo.js HOME PWD

You will see the following output:

[secondary_label Output] 
/home/sammy
/home/sammy/first-program

The forEach function ensures that each command line argument is printed in the args array.

Now you have a way to retrieve the variables that the user requests, but we still need to handle cases where the user enters bad data.

Step 8 – Handling Unspecified Input

To see what happens if you give the program an argument that is not a valid environment variable, run the following:

node echo.js HOME PWD NOT_DEFINED

The output will be similar to the following figure:

[secondary_label Output] 
/home/sammy
/home/sammy/first-program
undefined

The first two lines are printed as expected, and the last line is just undefined. In JavaScript, an undefined value means that a variable or property has not been assigned a value. Since NOT_DEFINED is not a valid environment variable, it is shown as undefined.

If the user's command line argument is not found in the environment, it would be more useful for the user to see an error message.

Open echo.js for editing:

nano echo.js

Edit echo.js so that it contains the following code:

const args = process.argv.slice(2);
args.forEach(arg => {
let envVar = process.env[arg];
if (envVar === undefined) {
console.error(`Could not find "${arg}" in environment`);
} else {
console.log(envVar);
}
});

Here, you have modified the callback function provided to forEach to do the following:

  1. Get the value of the command line arguments in the environment and store it in an env Var variable.
  2. Check if the envVar value is undefined.
  3. If envVar is not defined, we print a helpful message indicating that it was not found.
  4. If the environment variable is found, we print its value.

Now run the following command once again:

node echo.js HOME PWD NOT_DEFINED

This time the output will be:

[secondary_label Output] 
/home/sammy
/home/sammy/first-program
Could not find "NOT_DEFINED" in environment

Now when you provide a command line argument that is not an environment variable, you will get a clear error message stating this.

Result

Your first program displayed “Hello World” on the screen, and now you’ve written a Node.js command-line tool that reads user arguments to display environment variables.

If you want to take this further, you can change the behavior of this program even further. For example, you might want to validate command line arguments before printing. If an argument is undefined, you can return an error and the user will only receive output if all arguments are valid environment variables.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like