- Assertion Testing
- Async Hooks
- Buffer
- C++ Addons
- C/C++ Addons - N-API
- Child Processes
- Cluster
- Command Line Options
- Console
- Crypto
- Debugger
- Deprecated APIs
- DNS
- Domain
- ECMAScript Modules
- Errors
- Events
- File System
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules
- Net
- OS
- Path
- Performance Hooks
- Process
- Punycode
- Query Strings
- Readline
- REPL
- Stream
- String Decoder
- Timers
- TLS/SSL
- Trace Events
- TTY
- UDP/Datagram
- URL
- Utilities
- V8
- VM
- Worker Threads
- Zlib
Node.js v10.24.1 Documentation
Table of Contents
REPL#
The 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:
const repl = require('repl');
Design and Features#
The 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,
simplistic Emacs-style line editing, multi-line inputs, ANSI-styled output,
saving and restoring current REPL session state, error recovery, and
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, entering the.breakcommand (or pressing the<ctrl>-Ckey combination) will abort further input or processing of that expression..clear- Resets the REPLcontextto an empty object and clears any multi-line expression currently 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>-Dto finish,<ctrl>-Cto 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.breakcommand. When pressed twice on a blank line, has the same effect as the.exitcommand.<ctrl>-D- Has the same effect as the.exitcommand.<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. 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:
const repl = require('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():
const repl = require('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('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 do not emit the
'uncaughtException'event. - Trying to use
process.setUncaughtExceptionCaptureCallback()throws anERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTUREerror.
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');
Error: foo
> _error.message
'foo'
await keyword#
With the --experimental-repl-await command line option specified,
experimental support for the await keyword is enabled.
> await Promise.resolve(123)
123
> await Promise.reject(new Error('REPL await'))
Error: REPL await
at repl:1:45
> const timeout = util.promisify(setTimeout);
undefined
> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
1002
undefined
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.
The following illustrates a hypothetical example of a REPL that performs translation of text from one language to another:
const repl = require('repl');
const { Translator } = require('translator');
const myTranslator = new Translator('en', 'fr');
function myEval(cmd, context, filename, callback) {
callback(null, myTranslator.translate(cmd));
}
repl.start({ prompt: '> ', eval: myEval });
Recoverable Errors#
As a user is typing input into the REPL prompt, pressing the <enter> key will
send 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;
}
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 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.
It is possible to fully customize the output of a repl.REPLServer instance
by passing a new function in using the writer option on construction. The
following example, for instance, simply converts any input text to upper case:
const repl = require('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#
The repl.REPLServer class inherits from the readline.Interface class.
Instances of repl.REPLServer are created using the repl.start() method and
should not be created 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. The listener
callback is invoked without any arguments.
replServer.on('exit', () => {
console.log('Received "exit" event from repl!');
process.exit();
});