REPL
History
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';
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.
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.
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.
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.
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;
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,
});
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');
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.
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'
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
History
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.
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:
Property | Type | Description |
---|---|---|
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: |
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 });
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;
}
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
]
>
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();
}
class REPLServer 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);
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();
});
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);
When this code is executed, the global 'm'
variable can be modified but then reset to its initial value using the .clear
command:
$ ./node example.js
> m
'test'
> m = 1
1
> m
1
> .clear
Clearing context...
> m
'test'
>
replServer.defineCommand(keyword, cmd)
Property | Type | Description |
---|---|---|
keyword | <string> | The command keyword (without a leading . character). |
cmd | <Object> | <Function> | The function to invoke when the command is processed. |
The replServer.defineCommand()
method is used to add new .
-prefixed commands to the REPL instance. Such commands are invoked by typing a .
followed by the keyword
. The cmd
is either a Function
or an Object
with the following properties:
Property | Type | Description |
---|---|---|
help | <string> | Help text to be displayed when .help is entered (Optional). |
action | <Function> | The function to execute, optionally accepting a single string argument. |
The following example shows two new commands added to the REPL instance:
import repl from 'node:repl';
const replServer = repl.start({ prompt: '> ' });
replServer.defineCommand('sayhello', {
help: 'Say hello',
action(name) {
this.clearBufferedCommand();
console.log(`Hello, ${name}!`);
this.displayPrompt();
},
});
replServer.defineCommand('saybye', function saybye() {
console.log('Goodbye!');
this.close();
});
The new commands can then be used from within the REPL instance:
> .sayhello Node.js User
Hello, Node.js User!
> .saybye
Goodbye!
replServer.displayPrompt(preserveCursor?)
Property | Type | Description |
---|---|---|
preserveCursor | <boolean> | - |
The replServer.displayPrompt()
method readies the REPL instance for input from the user, printing the configured prompt
to a new line in the output
and resuming the input
to accept new input.
When multi-line input is being entered, a pipe '|'
is printed rather than the 'prompt'.
When preserveCursor
is true
, the cursor placement will not be reset to 0
.
The replServer.displayPrompt
method is primarily intended to be called from within the action function for commands registered using the replServer.defineCommand()
method.
replServer.clearBufferedCommand()
The replServer.clearBufferedCommand()
method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using the replServer.defineCommand()
method.
replServer.setupHistory(historyConfig, callback)
Property | Type | Description | |||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
historyConfig | <Object> | <string> | the path to the history file If it is a string, it is the path to the history file. If it is an object, it can have the following properties: | |||||||||||||||||||||
| |||||||||||||||||||||||
callback | <Function> | called when history writes are ready or upon error (Optional if provided as onHistoryFileLoaded in historyConfig ) | |||||||||||||||||||||
|
Initializes a history log file for the REPL instance. When executing the Node.js binary and using the command-line REPL, a history file is initialized by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically.
repl.builtinModules
History
module.builtinModules
instead.Property | Type | Description |
---|---|---|
- | <string[]> | - |
A list of the names of some Node.js modules, e.g., 'http'
.
repl.start
History
Added the possibility to add/edit/remove multilines while adding a multiline command.
The multi-line indicator is now "|" instead of "...". Added support for multi-line history. It is now possible to "fix" multi-line commands with syntax errors by visiting the history and editing the command. When visiting the multiline history from an old node version, the multiline structure is not preserved.
The preview
option is now available.
The terminal
option now follows the default description in all cases and useColors
checks hasColors()
if available.
The REPL_MAGIC_MODE
replMode
was removed.
The breakEvalOnSigint
option is supported now.
The options
parameter is optional now.
repl.start(options?): repl.REPLServer
Property | Type | Description | |||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options | <Object> | <string> | - | |||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||
Returns | <repl.REPLServer> | - |
The repl.start()
method creates and starts a repl.REPLServer
instance.
If options
is a string, then it specifies the input prompt:
import repl from 'node:repl';
// a Unix style prompt
repl.start('$ ');
Node.js itself uses the node:repl
module to provide its own interactive interface for executing JavaScript. This can be used by executing the Node.js binary without passing any arguments (or by passing the -i
argument):
$ node
> const a = [1, 2, 3];
undefined
> a
[ 1, 2, 3 ]
> a.forEach((v) => {
... console.log(v);
... });
1
2
3
Various behaviors of the Node.js REPL can be customized using the following environment variables:
NODE_REPL_HISTORY
: When a valid path is given, persistent REPL history will be saved to the specified file rather than.node_repl_history
in the user's home directory. Setting this value to''
(an empty string) will disable persistent REPL history. Whitespace will be trimmed from the value. On Windows platforms environment variables with empty values are invalid so set this variable to one or more spaces to disable persistent REPL history.NODE_REPL_HISTORY_SIZE
: Controls how many lines of history will be persisted if history is available. Must be a positive number. Default:1000
.NODE_REPL_MODE
: May be either'sloppy'
or'strict'
. Default:'sloppy'
, which will allow non-strict mode code to be run.
By default, the Node.js REPL will persist history between node
REPL sessions by saving inputs to a .node_repl_history
file located in the user's home directory. This can be disabled by setting the environment variable NODE_REPL_HISTORY=''
.
For advanced line-editors, start Node.js with the environment variable NODE_NO_READLINE=1
. This will start the main and debugger REPL in canonical terminal settings, which will allow use with rlwrap
.
For example, the following can be added to a .bashrc
file:
alias node="env NODE_NO_READLINE=1 rlwrap node"
It is possible to create and run multiple REPL instances against a single running instance of Node.js that share a single global
object (by setting the useGlobal
option to true
) but have separate I/O interfaces.
The following example, for instance, provides separate REPLs on stdin
, a Unix socket, and a TCP socket, all sharing the same global
object:
import net from 'node:net';
import repl from 'node:repl';
import process from 'node:process';
import fs from 'node:fs';
let connections = 0;
repl.start({
prompt: 'Node.js via stdin> ',
useGlobal: true,
input: process.stdin,
output: process.stdout,
});
const unixSocketPath = '/tmp/node-repl-sock';
// If the socket file already exists let's remove it
fs.rmSync(unixSocketPath, { force: true });
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via Unix socket> ',
useGlobal: true,
input: socket,
output: socket,
}).on('exit', () => {
socket.end();
});
}).listen(unixSocketPath);
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via TCP socket> ',
useGlobal: true,
input: socket,
output: socket,
}).on('exit', () => {
socket.end();
});
}).listen(5001);
Running this application from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. telnet
, for instance, is useful for connecting to TCP sockets, while socat
can be used to connect to both Unix and TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, it is possible to connect to a long-running Node.js process without restarting it.
This is an example on how to run a "full-featured" (terminal) REPL using net.Server
and net.Socket
The following script starts an HTTP server on port 1337
that allows clients to establish socket connections to its REPL instance.
// repl-server.js
import repl from 'node:repl';
import net from 'node:net';
net
.createServer((socket) => {
const r = repl.start({
prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,
input: socket,
output: socket,
terminal: true,
useGlobal: false,
});
r.on('exit', () => {
socket.end();
});
r.context.socket = socket;
})
.listen(1337);
While the following implements a client that can create a socket connection with the above defined server over port 1337
.
// repl-client.js
import net from 'node:net';
import process from 'node:process';
const sock = net.connect(1337);
process.stdin.pipe(sock);
sock.pipe(process.stdout);
sock.on('connect', () => {
process.stdin.resume();
process.stdin.setRawMode(true);
});
sock.on('close', () => {
process.stdin.setRawMode(false);
process.stdin.pause();
sock.removeListener('close', done);
});
process.stdin.on('end', () => {
sock.destroy();
console.log();
});
process.stdin.on('data', (b) => {
if (b.length === 1 && b[0] === 4) {
process.stdin.emit('end');
}
});
To run the example open two different terminals on your machine, start the server with node repl-server.js
in one terminal and node repl-client.js
on the other.
Original code from https://gist.github.com/TooTallNate/2209310.
This is an example on how to run a REPL instance over curl()
The following script starts an HTTP server on port 8000
that can accept a connection established via curl()
.
import http from 'node:http';
import repl from 'node:repl';
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'multipart/octet-stream');
repl.start({
prompt: 'curl repl> ',
input: req,
output: res,
terminal: false,
useColors: true,
useGlobal: false,
});
});
server.listen(8000);
When the above script is running you can then use curl()
to connect to the server and connect to its REPL instance by running curl --no-progress-meter -sSNT. localhost:8000
.
Warning This example is intended purely for educational purposes to demonstrate how Node.js REPLs can be started using different I/O streams. It should not be used in production environments or any context where security is a concern without additional protective measures. If you need to implement REPLs in a real-world application, consider alternative approaches that mitigate these risks, such as using secure input mechanisms and avoiding open network interfaces.
Original code from https://gist.github.com/TooTallNate/2053342.