How Does Node.js Work?
First Program in Node.js
Before starting to work, you’ll need to select a working directory. On Unix systems, it is very easy to navigate to the user’s directory with the following command:
cd ~
To find out the path of the directory where you are located, use the
pwd
command.
Next, create a directory named “greeting” and enter it with the following command:
mkdir greeting && cd greeting
Create an application that greets the user and displays the current year each time it runs. Then, in the working directory, create a file named index.js
with the following content:
const name = 'Gustavo';
const year = new Date().getFullYear();
console.log(`Hey ${name}, we are in ${year}`);
In the previous code snippet, variable interpolation is used with JavaScript Template Strings.
Run the program with the following command:
node index.js
Congratulations! You have created your first program in Node.js.
What is REPL?
In the previous section, you saw how to run a JavaScript file with Node.js using the following command:
node index.js
Use the node
executable with the argument index.js
. Remember, Node.js can not only be used to run applications but also as a command-line program to evaluate expressions; this is called REPL (Read Eval Print Loop). It is executed as follows:
node
You can write expressions like 1+1
and press the ENTER
key or expressions like "A" === "A"
and press the ENTER
key. As its name suggests, for each of the entered commands, it performs the following operations:
- Reads the expression
- Evaluates the expression
- Prints the result
- Repeats the process
To exit this cycle, you can use the Ctrl+C
key combination twice, or you can use the Ctrl+D
key combination, or the expression process.exit(0)
.
You can even write a complete program.
node (ENTER)
var a = 0; (ENTER)
if (a === 0) { (ENTER)
console.log("a == 0"); (ENTER)
} (ENTER)
The word
ENTER
is placed to indicate when to press that key.
You will notice that when you write the expression if (a === 0) {
and press the ENTER
key, it is not immediately evaluated, as the presence of {
indicates the beginning of a block. When you enter }
, the entire block is evaluated.
For greater convenience, you can enter the command .editor
to enable a command-line editor to create the program more easily:
node
> .editor
// Entering editor mode (^D to finish, ^C to cancel)
All the commands listed below can be used within the REPL command line and NOT in the system command line:
- The
TAB
key shows a list of all available functions. - The
.break
command orCTRL+C
allows you to add a new line. - Once the session ends, all variables are lost, but you can save them to a file with the following command
.save [file-name]
. - Similarly, you can load them again with the
.load [file-name]
command. - A list of other commands is available with the
.help
command.
As you can see, Node REPL is very useful for quickly testing functionalities or even debugging a program.
For more information:
Global Object
In a Node.js application, several global objects and functions are available throughout the application that don’t need the inclusion of any module. Examples of these are:
console
: Allows printing text to the console.process
: Provides access to all information about the running Node.js process.__filename
and__dirname
: Used to obtain information about the directory and file being executed.module
,exports
, andrequire
: Used to export and import modules.
There is a global object also named global
. This particular object is at the top level of the “scope” of each Node.js application. An analogy with the Web browser environment would be the window
object. Due to this characteristic, it is often used to store variables and access them in other parts of the application; unfortunately, this is not a good practice since you cannot have full control over them as they can be overwritten in any part of the application, leading to undesired results.
For more information:
Process Object
The process object provides information about the current process in which the Node.js application is running. Therefore, it is very important to know about it, as you can obtain information such as the Node.js version, core libraries, user directory, temporary directory, PATH object, and others.
To see the information contained in the process object:
node -p "process"
The
-p
flag evaluates and prints the expression provided as an argument
As you can see, it contains a lot of information, but you can directly access specific information, as it is actually a JavaScript object within the Node.js application. An example would be information about the core libraries:
node -p "process.versions"
For more information:
Command Line Arguments
Each time a program is run with Node.js, it processes the arguments and stores them in the process.argv
object.
In the greeting
application, edit the content of the index.js
file and add the following line at the end:
console.log(process.argv);
Run the application with the following command:
node index.js
The following is the output in the console:
[ '/Users/.../.nvm/versions/node/.../bin/node',
'/Users/.../02-greeting/index.js' ]
The directory paths have been modified to omit irrelevant information and replaced with ellipses
...
The process.argv
object is an array that stores each argument in each position. In this case, the first element is the location of the Node.js executable, and the second is the entry file of the application. The arguments are interpreted as they are separated by spaces.
Modify the index.js
file as follows:
const args = process.argv.slice(2);
const [name = 'Friend'] = args;
const hour = new Date().getHours();
// Ask for hours range
if (hour >= 6 && hour < 12) {
console.log(`Good morning ${name}`);
} else if (hour >= 12 && hour < 18) {
console.log(`Good afternoon ${name}`);
} else if (hour >= 18 && hour < 23) {
console.log(`Good evening ${name}`);
} else {
console.log(`Good night ${name}`);
}
The following changes were made:
- The
args
variable stores a portion of the arguments array originally from theargv
property, ignoring the first two elements with theslice
method. - Array destructuring is used to get the first element of the array, and if it does not exist, it is assigned the default value of
"Friend"
. - The local time is obtained.
- Finally, depending on the value of the local time, a message is printed greeting the person whose name was passed as an argument during the program execution.
Run the application with the following command:
node index.js Gustavo