Skip to main content
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.
import repl from 'node:repl';
// or
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. 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
  • Customizable evaluation functions

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)

Key Combinations

The following key combinations have 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

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.

JavaScript Expressions

The default evaluator supports direct evaluation of JavaScript expressions:
> 1 + 1
2
> const m = 2
undefined
> m + 1
3

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;
Properties in the context object appear as local within the REPL:
$ node repl_test.js
> m
'message'

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');

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
Similarly, _error will refer to the last seen error, if there was any.

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
One known limitation of using the await keyword in the REPL is that it will invalidate the lexical scoping of the const keywords.

Starting the REPL

repl.start([options])

The repl.start() method creates and starts a repl.REPLServer instance. Parameters:
  • options
    • prompt The input prompt to display. Default: '> '
    • input The Readable stream from which REPL input will be read. Default: process.stdin
    • output The Writable stream to which REPL output will be written. Default: process.stdout
    • terminal If true, specifies that the output should be treated as a TTY terminal
    • eval The function to be used when evaluating each given line of input
    • useColors If true, specifies that the default writer function should include ANSI color styling to REPL output
    • useGlobal If true, specifies that the default evaluation function will use the JavaScript global as the context. Default: false
    • ignoreUndefined If true, specifies that the default writer will not output the return value of a command if it evaluates to undefined. Default: false
    • replMode A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode
    • breakEvalOnSigint Stop evaluating the current piece of code when SIGINT is received. Default: false
Returns:
import repl from 'node:repl';

// a Unix style prompt
repl.start('$ ');

Class: REPLServer

Instances of repl.REPLServer are created using the repl.start() method or directly using the JavaScript new keyword.

Event: ‘exit’

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.
replServer.on('exit', () => {
  console.log('Received "exit" event from repl!');
  process.exit();
});

Event: ‘reset’

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.
import repl from 'node:repl';

function initializeContext(context) {
  context.m = 'test';
}

const r = repl.start({ prompt: '> ' });
initializeContext(r.context);

r.on('reset', initializeContext);

replServer.defineCommand(keyword, cmd)

The replServer.defineCommand() method is used to add new .-prefixed commands to the REPL instance. Parameters:
  • keyword The command keyword (without a leading . character)
  • cmd The function to invoke when the command is processed
    • help Help text to be displayed when .help is entered (Optional)
    • action The function to execute, optionally accepting a single string argument
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.displayPrompt([preserveCursor])

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.

The Node.js REPL

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

Environment Variable Options

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
  • 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

Persistent History

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=''.