How to use the Node.js REPL
node command is the one we use to run our Node.js scripts:
If we run the
node command without any script to execute or without any arguments, we start a REPL session:
If you try it now in your terminal, this is what happens:
The command stays in idle mode and waits for us to enter something.
Tip: if you are unsure how to open your terminal, google "How to open terminal on your-operating-system".
Start simple and enter
The first value,
test, is the output we told the console to print, then we get
undefined which is the return value of running
Node read this line of code, evaluated it, printed the result, and then went back to waiting for more lines of code. Node will loop through these three steps for every piece of code we execute in the REPL until we exit the session. That is where the REPL got its name.
Note the difference in the outputs of the above two lines. The Node REPL printed
undefined after executed
console.log(), while on the other hand, it just printed the result of
In some cases, the code you want to test might need multiple lines. For example, say you want to define a function that generates a random number, in the REPL session type in the following line and press enter:
The Node REPL is smart enough to determine that you are not done writing your code yet, and it will go into a multi-line mode for you to type in more code. Now finish your function definition and press enter:
If after some code you type
_, that is going to print the result of the last operation.
If you press the
up arrow key, you will get access to the history of the previous lines of code executed in the current, and even previous REPL sessions.
The REPL has some special commands, all starting with a dot
.. They are
.help: shows the dot commands help
.break: when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C.
.clear: resets the REPL context to an empty object and clears any multi-line expression currently being input.
.save: saves all you entered in the REPL session to a file (specify the filename)
.exit: exits the repl (same as pressing ctrl-C two times)
The REPL knows when you are typing a multi-line statement without the need to invoke
For example if you start typing an iteration like this:
and you press
enter, the REPL will go to a new line that starts with 3 dots, indicating you can now continue to work on that block.
If you type
.break at the end of a line, the multiline mode will stop and the statement will not be executed.
Using the repl variable we can perform various operations. To start the REPL command prompt, type in the following line
Run the file in the command line.
You can pass a string which shows when the REPL starts. The default is '> ' (with a trailing space), but we can define custom prompt.
You can display a message while exiting the REPL
You can read more about the REPL module in the repl documentation.