Working with Node.js REPL
1. Starting REPL Session
| Command | Purpose |
|---|---|
node | Start REPL |
node -i -e "code" | Run code then drop into REPL |
NODE_REPL_HISTORY=~/.node_history | Persist history across sessions |
2. Evaluating JavaScript Expressions
| Input | Result |
|---|---|
1 + 2 | 3 |
const x = 5 | undefined (declaration) |
await fetch("https://api.example.com") | Top-level await supported v18+ |
3. Using Multi-Line Input (.editor)
Example: Editor mode
> .editor
// Entering editor mode (Ctrl+D to finish, Ctrl+C to cancel)
function add(a, b) {
return a + b;
}
^D
> add(2, 3)
5
| Key | Action |
|---|---|
Ctrl+D | Finish input |
Ctrl+C | Cancel |
4. Navigating REPL History
| Key | Action |
|---|---|
↑ / ↓ | Previous / next command |
Ctrl+R | Reverse history search |
NODE_REPL_HISTORY_SIZE | Number of entries kept |
5. Using Tab Completion
| Action | Behavior |
|---|---|
Math.<Tab> | List all properties of Math |
req<Tab> | Complete identifier name |
./fil<Tab> | Path completion in require |
6. Using Underscore for Last Result (_)
Example: Underscore variables
> 2 + 3
5
> _ * 2
10
> throw new Error("oops")
> _error.message
"oops"
| Variable | Holds |
|---|---|
_ | Last evaluated value |
_error | Last uncaught error |
7. Inspecting Objects in REPL
| Setting | Effect |
|---|---|
util.inspect.defaultOptions.depth = null | Unlimited depth |
util.inspect(obj, { colors: true }) | Colorized output |
console.dir(obj, { depth: 4 }) | Custom depth |
8. Loading External Files (.load)
| Command | Action |
|---|---|
.load <file> | Read file and execute line by line |
9. Saving REPL Session (.save)
| Command | Action |
|---|---|
.save session.js | Write history to file |
.load session.js | Replay later |
10. Clearing REPL Context (.clear)
| Command | Action |
|---|---|
.clear | Reset REPL context (alias for .break in older versions) |
11. Using REPL Commands (.help, .exit, .break)
| Command | Purpose |
|---|---|
.help | List all REPL commands |
.exit / Ctrl+D | Quit REPL |
.break / Ctrl+C | Abort current multi-line input |
.editor | Multi-line editor mode |