/

How to Use the Node.js REPL

How to Use the Node.js REPL

The Node.js REPL (Read-Evaluate-Print-Loop) is a powerful tool for quickly exploring and testing Node.js features. This guide will show you how to use the Node.js REPL effectively.

Running the Node.js REPL

To start the Node.js REPL, open your terminal and execute the node command without specifying a file:

1
node

This will start the REPL, and you’ll see a prompt (>). The REPL is now ready to accept and evaluate JavaScript code.

Trying Out JavaScript Code

You can start entering JavaScript code at the REPL prompt and see the results immediately. For example, enter the following code:

1
> console.log('test')

The output will be:

1
2
test
undefined

Here, test is the output of the console.log() statement, and undefined is the return value of that statement.

Autocompletion with Tab

One useful feature of the Node.js REPL is autocompletion. As you write your code, you can press the tab key to have the REPL autocomplete your code based on existing variables or predefined objects.

Exploring JavaScript Objects

You can explore the properties and methods of JavaScript classes or objects in the REPL. For example, enter Number. and press tab, and the REPL will display all the available properties and methods for the Number class.

Inspecting Global Objects

To inspect the global objects available in the Node.js environment, type global. and press tab. This will display all the global objects and their properties.

Using the _ Variable

The REPL provides a special variable _ that represents the result of the last operation. You can access the value of _ to reuse it in subsequent code.

Dot Commands

The Node.js REPL also supports dot commands, which start with a dot (.). Here are some useful dot commands:

  • .help: Displays the help for dot commands.
  • .editor: Enables the editor mode for writing multiline JavaScript code. Press ctrl-D to run the code.
  • .break: Aborts the input of a multiline expression.
  • .clear: Resets the REPL context and clears any multiline expression.
  • .load: Loads a JavaScript file relative to the current working directory.
  • .save: Saves the REPL session to a file.
  • .exit: Exits the REPL.

The REPL automatically detects when you start typing a multiline statement and doesn’t require invoking .editor. You can use .break to stop a multiline mode and execute the statement.

That’s it! Now you know how to use the Node.js REPL to quickly explore and test JavaScript code.

tags: [“Node.js”, “REPL”, “JavaScript”, “autocompletion”, “dot commands”]