Node.js v24.0.1 documentation
- Node.js v24.0.1
- Table of contents
-
Index
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:module
API - Modules: Packages
- Modules: TypeScript
- Net
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Single executable applications
- SQLite
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- Other versions
- Options
REPL#
Source Code: lib/repl.js
The node:repl
module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
applications. It can be accessed using:
import repl from 'node:repl';
const repl = require('node:repl');
Design and features#
The node:repl
module exports the repl.REPLServer
class. While running,
instances of repl.REPLServer
will accept individual lines of user input,
evaluate those according to a user-defined evaluation function, then output the
result. Input and output may be from stdin
and stdout
, respectively, or may
be connected to any Node.js stream.
Instances of repl.REPLServer
support automatic completion of inputs,
completion preview, simplistic Emacs-style line editing, multi-line inputs,
ZSH-like reverse-i-search, ZSH-like substring-based history search,
ANSI-styled output, saving and restoring current REPL session state, error
recovery, and customizable evaluation functions. Terminals that do not support
ANSI styles and Emacs-style line editing automatically fall back to a limited
feature set.
Commands and special keys#
The following special commands are supported by all REPL instances:
.break
: When in the process of inputting a multi-line expression, enter the.break
command (or press Ctrl+C) to abort further input or processing of that expression..clear
: Resets the REPLcontext
to an empty object and clears any multi-line expression being input..exit
: Close the I/O stream, causing the REPL to exit..help
: Show this list of special commands..save
: Save the current REPL session to a file:> .save ./file/to/save.js
.load
: Load a file into the current REPL session.> .load ./file/to/load.js
.editor
: Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).
> .editor
// Entering editor mode (^D to finish, ^C to cancel)
function welcome(name) {
return `Hello ${name}!`;
}
welcome('Node.js User');
// ^D
'Hello Node.js User!'
>
The following key combinations in the REPL have these special effects:
- Ctrl+C: When pressed once, has the same effect as the
.break
command. When pressed twice on a blank line, has the same effect as the.exit
command. - Ctrl+D: Has the same effect as the
.exit
command. - Tab: When pressed on a blank line, displays global and local (scope) variables. When pressed while entering other input, displays relevant autocompletion options.
For key bindings related to the reverse-i-search, see reverse-i-search
.
For all other key bindings, see TTY keybindings.
Default evaluation#
By default, all instances of repl.REPLServer
use an evaluation function
that evaluates JavaScript expressions and provides access to Node.js built-in
modules. This default behavior can be overridden by passing in an alternative
evaluation function when the repl.REPLServer
instance is created.
JavaScript expressions#
The default evaluator supports direct evaluation of JavaScript expressions:
> 1 + 1
2
> const m = 2
undefined
> m + 1
3
Unless otherwise scoped within blocks or functions, variables declared
either implicitly or using the const
, let
, or var
keywords
are declared at the global scope.
Global and local scope#
The default evaluator provides access to any variables that exist in the global
scope. It is possible to expose a variable to the REPL explicitly by assigning
it to the context
object associated with each REPLServer
:
import repl from 'node:repl';
const msg = 'message';
repl.start('> ').context.m = msg;
const repl = require('node:repl');
const msg = 'message';
repl.start('> ').context.m = msg;
Properties in the context
object appear as local within the REPL:
$ node repl_test.js
> m
'message'
Context properties are not read-only by default. To specify read-only globals,
context properties must be defined using Object.defineProperty()
:
import repl from 'node:repl';
const msg = 'message';
const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
configurable: false,
enumerable: true,
value: msg,
});
const repl = require('node:repl');
const msg = 'message';
const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
configurable: false,
enumerable: true,
value: msg,
});
Accessing core Node.js modules#
The default evaluator will automatically load Node.js core modules into the
REPL environment when used. For instance, unless otherwise declared as a
global or scoped variable, the input fs
will be evaluated on-demand as
global.fs = require('node:fs')
.
> fs.createReadStream('./some/file');
Global uncaught exceptions#
The REPL uses the domain
module to catch all uncaught exceptions for that
REPL session.
This use of the domain
module in the REPL has these side effects:
-
Uncaught exceptions only emit the
'uncaughtException'
event in the standalone REPL. Adding a listener for this event in a REPL within another Node.js program results inERR_INVALID_REPL_INPUT
.const r = repl.start(); r.write('process.on("uncaughtException", () => console.log("Foobar"));\n'); // Output stream includes: // TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException` // cannot be used in the REPL r.close();
-
Trying to use
process.setUncaughtExceptionCaptureCallback()
throws anERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE
error.
Assignment of the _
(underscore) variable#
The default evaluator will, by default, assign the result of the most recently
evaluated expression to the special variable _
(underscore).
Explicitly setting _
to a value will disable this behavior.
> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
Expression assignment to _ now disabled.
4
> 1 + 1
2
> _
4
Similarly, _error
will refer to the last seen error, if there was any.
Explicitly setting _error
to a value will disable this behavior.
> throw new Error('foo');
Uncaught Error: foo
> _error.message
'foo'
await
keyword#
Support for the await
keyword is enabled at the top level.
> await Promise.resolve(123)
123
> await Promise.reject(new Error('REPL await'))
Uncaught Error: REPL await
at REPL2:1:54
> const timeout = util.promisify(setTimeout);
undefined
> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
1002
undefined
One known limitation of using the await
keyword in the REPL is that
it will invalidate the lexical scoping of the const
keywords.
For example:
> const m = await Promise.resolve(123)
undefined
> m
123
> m = await Promise.resolve(234)
234
// redeclaring the constant does error
> const m = await Promise.resolve(345)
Uncaught SyntaxError: Identifier 'm' has already been declared
--no-experimental-repl-await
shall disable top-level await in REPL.
Reverse-i-search#
The REPL supports bi-directional reverse-i-search similar to ZSH. It is triggered with Ctrl+R to search backward and Ctrl+S to search forwards.
Duplicated history entries will be skipped.
Entries are accepted as soon as any key is pressed that doesn't correspond with the reverse search. Cancelling is possible by pressing Esc or Ctrl+C.
Changing the direction immediately searches for the next entry in the expected direction from the current position on.
Custom evaluation functions#
When a new repl.REPLServer
is created, a custom evaluation function may be
provided. This can be used, for instance, to implement fully customized REPL
applications.
An evaluation function accepts the following four arguments:
code