REPL | Node.js v26.8.2 Documentation
https://nodejs.org/api/repl.html • 223 KB fetched
Open original page
REPL | Node.js v26.8.2 Documentation Skip to content
Node.js
* About this documentation
* Usage and example
* 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
* Environment Variables
* Errors
* Events
* File system
* FFI
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Iterable Streams API
* 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
* Virtual File System
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
*
Code repository and issue tracker
Node.js v26.8.2 documentation
* Node.js v26.8.2
* Table of contents
* REPL
* Design and features
* Commands and special keys
* Default evaluation
* JavaScript expressions
* Global and local scope
* Accessing core Node.js modules
* Global uncaught exceptions
* Assignment of the _ (underscore) variable
* await keyword
* Reverse-i-search
* Custom evaluation functions
* Recoverable errors
* Customizing REPL output
* Class: REPLServer
* Event: 'exit'
* Event: 'reset'
* replServer.defineCommand(keyword, cmd)
* replServer.displayPrompt([preserveCursor])
* replServer.clearBufferedCommand()
* replServer.setupHistory(historyConfig, callback)
* repl.builtinModules
* repl.start([options])
* The Node.js REPL
* Environment variable options
* Persistent history
* Using the Node.js REPL with advanced line-editors
* Starting multiple REPL instances in the same process
* Examples
* Full-featured "terminal" REPL over net.Server and net.Socket
* REPL over curl
* Index
* Index
* About this documentation
* Usage and example
* 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
* Environment Variables
* Errors
* Events
* File system
* FFI
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Iterable Streams API
* 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
* Virtual File System
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Other versions
* 26.x
* 25.x
* 24.x LTS
* 23.x
* 22.x LTS
* 21.x
* 20.x
* 19.x
* 18.x
* 17.x
* 16.x
* 15.x
* 14.x
* 13.x
* 12.x
* 11.x
* 10.x
* 9.x
* 8.x
* 7.x
* 6.x
* 5.x
* 4.x
* 0.12.x
* 0.10.x
*
Options
*
View on single page
*
View as JSON
* Edit on GitHub
Table of contents
* REPL
* Design and features
* Commands and special keys
* Default evaluation
* JavaScript expressions
* Global and local scope
* Accessing core Node.js modules
* Global uncaught exceptions
* Assignment of the _ (underscore) variable
* await keyword
* Reverse-i-search
* Custom evaluation functions
* Recoverable errors
* Customizing REPL output
* Class: REPLServer
* Event: 'exit'
* Event: 'reset'
* replServer.defineCommand(keyword, cmd)
* replServer.displayPrompt([preserveCursor])
* replServer.clearBufferedCommand()
* replServer.setupHistory(historyConfig, callback)
* repl.builtinModules
* repl.start([options])
* The Node.js REPL
* Environment variable options
* Persistent history
* Using the Node.js REPL with advanced line-editors
* Starting multiple REPL instances in the same process
* Examples
* Full-featured "terminal" REPL over net.Server and net.Socket
* REPL over curl
REPL #
Source Code: lib/repl.js
Stability: 2 - Stable
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' ) ;
javascript copy
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 REPL context 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!'
>
console copy
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
console copy
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 ;
javascript copy
Properties in the context object appear as local within the REPL: $ node repl_test.js
> m
'message'
console copy
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 ,
} ) ;
javascript copy
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' ) ;
console copy
Global uncaught exceptions #
History Version Changes v12.3.0 The 'uncaughtException' event is from now on triggered if the repl is used as standalone program.
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 in ERR_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 () ;
js copy
*
Trying to use process.setUncaughtExceptionCaptureCallback() throws
an ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE error.
Assignment of the _ (underscore) variable #
History Version Changes v9.8.0 Added _error support.
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
console copy
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'
console copy
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
console copy
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
console copy
--no-experimental-repl-await shall disable top-level await in REPL.
Reverse-i-search #
Added in: v13.6.0, v12.17.0
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 <string> The code to be executed (e.g. 1 + 1 ).
* context <Object> The context in which the code is executed. This can either be the JavaScript global
context or a context specific to the REPL instance, depending on the useGlobal option.
* replResourceName <string> An identifier for the REPL resource associated with the current code
evaluation. This can be useful for debugging purposes.
* callback <Function> A function to invoke once the code evaluation is complete. The callback takes two parameters:
* An error object to provide if an error occurred during evaluation, or null / undefined if no error occurred.
* The result of the code evaluation (this is not relevant if an error is provided).
The following illustrates an example of a REPL that squares a given number, an error is instead printed
if the provided input is not actually a number: import repl from 'node:repl' ;
function byThePowerOfTwo ( number ) {
return number * number ;
}
function myEval ( code , context , replResourceName , callback ) {
if ( isNaN (code)) {
callback ( new Error ( ` ${ code . trim () } is not a number` )) ;
} else {
callback ( null , byThePowerOfTwo (code)) ;
}
}
repl . start ( { prompt : 'Enter a number: ' , eval : myEval } ) ;
const repl = require ( 'node:repl' ) ;
function byThePowerOfTwo ( number ) {
return number * number ;
}
function myEval ( code , context , replResourceName , callback ) {
if ( isNaN (code)) {
callback ( new Error ( ` ${ code . trim () } is not a number` )) ;
} else {
callback ( null , byThePowerOfTwo (code)) ;
}
}
repl . start ( { prompt : 'Enter a number: ' , eval : myEval } ) ;
javascript copy
Recoverable errors #
At the REPL prompt, pressing Enter sends the current line of input to
the eval function. In order to support multi-line input, the eval function
can return an instance of repl.Recoverable to the provided callback function: function myEval ( cmd , context , filename , callback ) {
let result ;
try {
result = vm . runInThisContext (cmd) ;
} catch (e) {
if ( isRecoverableError (e)) {
return callback ( new repl . Recoverable (e)) ;
}
}
callback ( null , result) ;
}
function isRecoverableError ( error ) {
if (error . name === 'SyntaxError' ) {
return / ^ (Unexpected end of input | Unexpected token) / . test (error . message) ;
}
return false ;
}
js copy
Customizing REPL output #
By default, repl.REPLServer instances format output using the
util.inspect() method before writing the output to the provided Writable
stream ( process.stdout by default). The showProxy inspection option is set
to true by default and the colors option is set to true depending on the
REPL's useColors option. The useColors boolean option can be specified at construction to instruct the
default writer to use ANSI style codes to colorize the output from the
util.inspect() method. If the REPL is run as standalone program, it is also possible to change the
REPL's inspection defaults from inside the REPL by using the
inspect.replDefaults property which mirrors the defaultOptions from
util.inspect() . > util.inspect.replDefaults.compact = false ;
false
> [ 1 ]
[
1
]
>
console copy
To fully customize the output of a repl.REPLServer instance pass in a new
function for the writer option on construction. The following example, for
instance, simply converts any input text to upper case: import repl from 'node:repl' ;
const r = repl . start ( { prompt : '> ' , eval : myEval , writer : myWriter } ) ;
function myEval ( cmd , context , filename , callback ) {
callback ( null , cmd) ;
}
function myWriter ( output ) {
return output . toUpperCase () ;
}
const repl = require ( 'node:repl' ) ;
const r = repl . start ( { prompt : '> ' , eval : myEval , writer : myWriter } ) ;
function myEval ( cmd , context , filename , callback ) {
callback ( null , cmd) ;
}
function myWriter ( output ) {
return output . toUpperCase () ;
}
javascript copy
Class: REPLServer #
Added in: v0.1.91
* options <Object> | <string> See repl.start()
* Extends: <readline.Interface>
Instances of repl.REPLServer are created using the repl.start() method
or directly using the JavaScript new keyword. import repl from 'node:repl' ;
const options = { useColors : true };
const firstInstance = repl . start (options) ;
const secondInstance = new repl . REPLServer (options) ;
const repl = require ( 'node:repl' ) ;
const options = { useColors : true };
const firstInstance = repl . start (options) ;
const secondInstance = new repl . REPLServer (options) ;
javascript copy
Event: 'exit' #
Added in: v0.7.7
The 'exit' event is emitted when the REPL is exited either by receiving the
.exit command as input, the user pressing Ctrl + C twice
to signal SIGINT ,
or by pressing Ctrl + D to signal 'end' on the input
stream. The listener
callback is invoked without any arguments. replServer . on ( 'exit' , () => {
console . log ( 'Received "exit" event from repl!' ) ;
process . exit () ;
} ) ;
js copy
Event: 'reset' #
Added in: v0.11.0
The 'reset' event is emitted when the REPL's context is reset. This occurs
whenever the .clear command is received as input unless the REPL is using
the default evaluator and the repl.REPLServer instance was created with the
useGlobal option set to true . The listener callback will be called with a
reference to the context object as the only argument. This can be used primarily to re-initialize REPL context to some pre-defined
state: import repl from 'node:repl' ;
function initializeContext ( context ) {
context . m = 'test' ;
}
const r = repl . start ( { prompt : '> ' } ) ;
initializeContext (r . context) ;
r . on ( 'reset' , initializeContext) ;
const repl = require ( 'n
Links found on this page
- Skip to content [direct]
- Node.js [direct]
- About this documentation [direct]
- Usage and example [direct]
- Assertion testing [direct]
- Asynchronous context tracking [direct]
- Async hooks [direct]
- Buffer [direct]
- C++ addons [direct]
- C/C++ addons with Node-API [direct]
- C++ embedder API [direct]
- Child processes [direct]
- Cluster [direct]
- Command-line options [direct]
- Console [direct]
- Crypto [direct]
- Debugger [direct]
- Deprecated APIs [direct]
- Diagnostics Channel [direct]
- DNS [direct]
- Domain [direct]
- Environment Variables [direct]
- Errors [direct]
- Events [direct]
- File system [direct]
- FFI [direct]
- Globals [direct]
- HTTP [direct]
- HTTP/2 [direct]
- HTTPS [direct]
- Inspector [direct]
- Internationalization [direct]
- Iterable Streams API [direct]
- Modules: CommonJS modules [direct]
- Modules: ECMAScript modules [direct]
- Modules: node:module API [direct]
- Modules: Packages [direct]
- Modules: TypeScript [direct]
- Net [direct]
- OS [direct]
- Path [direct]
- Performance hooks [direct]
- Permissions [direct]
- Process [direct]
- Punycode [direct]
- Query strings [direct]
- Readline [direct]
- Report [direct]
- Single executable applications [direct]
- SQLite [direct]
- Stream [direct]
- String decoder [direct]
- Test runner [direct]
- Timers [direct]
- TLS/SSL [direct]
- Trace events [direct]
- TTY [direct]
- UDP/datagram [direct]
- URL [direct]
- Utilities [direct]
- V8 [direct]
- Virtual File System [direct]
- VM [direct]
- WASI [direct]
- Web Crypto API [direct]
- Web Streams API [direct]
- Worker threads [direct]
- Zlib [direct]
- Code repository and issue tracker [direct]
- Index [direct]
- 26.x [direct]
- 25.x [direct]
- 24.x LTS [direct]
- 23.x [direct]
- 22.x LTS [direct]
- 21.x [direct]
- 20.x [direct]
- 19.x [direct]
- 18.x [direct]
- 17.x [direct]