Node.js REPL (Read-Eval-Print Loop: Interactive Interpreter)
The Node.js REPL represents a computer environment similar to the terminal in Windows or Unix/Linux shell, where we can enter commands and receive system responses.
Node comes with its own interactive interpreter, which can perform the following tasks:
- Read - Reads user input, parses the input JavaScript data structures, and stores them in memory.
- Execute - Executes the input data structures.
- Print - Outputs the result.
- Loop - Repeats the above steps until the user presses ctrl-c twice to exit.
The Node interactive interpreter is excellent for debugging JavaScript code.
Getting Started with REPL
We can start the Node terminal by entering the following command:
$ node
>
At this point, we can input simple expressions after the >
and press Enter to see the results.
Simple Expression Calculation
Next, let's perform simple mathematical operations in the Node.js REPL command line window:
$ node
> 1 + 4
5
> 5 / 2
2.5
> 3 * 6
18
> 4 - 1
3
> 1 + (2 * 3) - 4
3
>
Using Variables
You can store data in variables and use them when needed.
Variable declarations require the var keyword; otherwise, the variable will be printed directly.
Variables declared with the var keyword can be output using console.log()
.
$ node
> x = 10
10
> var y = 10
undefined
> x + y
20
> console.log("Hello World")
Hello World
undefined
> console.log("www.tutorialpro.org")
www.tutorialpro.org
undefined
Multi-line Expressions
Node REPL supports multi-line expressions, similar to JavaScript. Let's execute a do-while loop:
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while (x < 5);
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>
The three dots (...
) are automatically generated by the system. Press Enter to start a new line, and Node will automatically detect if the expression is continuous.
Underscore (_) Variable
You can use the underscore (_
) to get the result of the previous expression:
$ node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
>
REPL Commands
- ctrl + c - Exits the current terminal.
- ctrl + c pressed twice - Exits Node REPL.
- ctrl + d - Exits Node REPL.
- Up/Down Arrow - Views the history of input commands.
- tab - Lists the current commands.
- .help - Lists the usage commands.
- .break - Exits multi-line expressions.
- .clear - Exits multi-line expressions.
- .save - Saves the current Node REPL session to a specified file.
- .load - Loads the file content into the current Node REPL session.
Stopping REPL
As mentioned earlier, pressing ctrl + c twice will exit the REPL:
$ node
>
(^C again to quit)
>
Gif Demonstration
Next, we will demonstrate the example operation through a Gif image: