Mastering the Node.js REPL (part 1)
One of the tools I always had in my belt but never payed too much attention to is the Node.js REPL. REPL stands for Read-Eval-Print-Loop and that is basically what it does: It reads an input, evaluates it, prints the result and starts the process again. I used to only fire it when I needed to quickly test a regular expression or to try a forgotten API method. Then I realized I wasn’t taking full advantage of its potential.
The common way of starting the Node.js REPL is invoking the
node command with no arguments. The prompt will change and you can start typing. Node expects you to type an expression and will print the result of that expression:
The Node.js REPL also loads all the standard libraries in the global context so they are available to you:
Another cool trick often forgotten is the autocompletion key. The node REPL autocompletes commands when you hit the
<tab> key. Unfortunately this does not work with expressions:
The underscore character _
In the Node.js REPL you can reference the last value using the underscore character
Node.js REPL commands
There are some special commands that you can send to the REPL. These commands start with a dot:
.exit command finishes the REPL session. It’s the same thing as typing
.save and .load commands
.load are two useful commands when working with the REPL.
.save allows you to save your current REPL session. The output file is a list of every expression you’ve run in that session:
Saving a session
The output file is a list of expressions
Now we can load the session back into the REPL with the
Loading the session back into the REPL
.editor command is quite useful to type multi-line content, even though I haven’t found yet a way to navigate up and down the lines:
To get a list with he available commands you can use the
await within the REPL
This is a experimental feature available for node 10.x and beyond and it needs to be activated passing the special flag
By default, the expression history is persistent. Every expression you evaluate in the REPL will be stored in a
.node_repl_history in your
$HOME. This can be disabled setting the environment variable
NODE_REPL_HISTORY to an empty string.
Another cool trick you can do with the default REPL is wrapping the
rlwrap. For this, you need to set the
NODE_NO_READLINE to 1. You could make an alias for it:
alias node="env NODE_NO_READLINE=1 rlwrap node
Now if you hit
ctrl-r you can search your command history.
Wrapping it up (for now)
In this post we have covered the basics of the default node REPL. In the second part of this series we will use the standard Node.js
repl library to customize it. Stay tuned!