{ "type": "module", "source": "doc/api/repl.md", "modules": [ { "textRaw": "REPL", "name": "repl", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
The repl
module provides a Read-Eval-Print-Loop (REPL) implementation that\nis available both as a standalone program or includible in other applications.\nIt can be accessed using:
const repl = require('repl');\n
",
"modules": [
{
"textRaw": "Design and Features",
"name": "design_and_features",
"desc": "The repl
module exports the repl.REPLServer
class. While running,\ninstances of repl.REPLServer
will accept individual lines of user input,\nevaluate those according to a user-defined evaluation function, then output the\nresult. Input and output may be from stdin
and stdout
, respectively, or may\nbe connected to any Node.js stream.
Instances of repl.REPLServer
support automatic completion of inputs,\nsimplistic Emacs-style line editing, multi-line inputs, ANSI-styled output,\nsaving and restoring current REPL session state, error recovery, and\ncustomizable evaluation functions.
The following special commands are supported by all REPL instances:
\n.break
: When in the process of inputting a multi-line expression, entering\nthe .break
command (or pressing the <ctrl>-C
key combination) will abort\nfurther input or processing of that expression..clear
: Resets the REPL context
to an empty object and clears any\nmulti-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:\n> .save ./file/to/save.js
.load
: Load a file into the current REPL session.\n> .load ./file/to/load.js
.editor
: Enter editor mode (<ctrl>-D
to finish, <ctrl>-C
to cancel).> .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>\n
\nThe following key combinations in the REPL have these special effects:
\n<ctrl>-C
: When pressed once, has the same effect as the .break
command.\nWhen pressed twice on a blank line, has the same effect as the .exit
\ncommand.<ctrl>-D
: Has the same effect as the .exit
command.<tab>
: When pressed on a blank line, displays global and local (scope)\nvariables. When pressed while entering other input, displays relevant\nautocompletion options.By default, all instances of repl.REPLServer
use an evaluation function\nthat evaluates JavaScript expressions and provides access to Node.js' built-in\nmodules. This default behavior can be overridden by passing in an alternative\nevaluation function when the repl.REPLServer
instance is created.
The default evaluator supports direct evaluation of JavaScript expressions:
\n> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n
\nUnless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const
, let
, or var
keywords\nare declared at the global scope.
The default evaluator provides access to any variables that exist in the global\nscope. It is possible to expose a variable to the REPL explicitly by assigning\nit to the context
object associated with each REPLServer
:
const repl = require('repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n
\nProperties in the context
object appear as local within the REPL:
$ node repl_test.js\n> m\n'message'\n
\nContext properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using Object.defineProperty()
:
const repl = require('repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n configurable: false,\n enumerable: true,\n value: msg\n});\n
",
"type": "module",
"displayName": "Global and Local Scope"
},
{
"textRaw": "Accessing Core Node.js Modules",
"name": "accessing_core_node.js_modules",
"desc": "The default evaluator will automatically load Node.js core modules into the\nREPL environment when used. For instance, unless otherwise declared as a\nglobal or scoped variable, the input fs
will be evaluated on-demand as\nglobal.fs = require('fs')
.
> fs.createReadStream('./some/file');\n
",
"type": "module",
"displayName": "Accessing Core Node.js Modules"
},
{
"textRaw": "Global Uncaught Exceptions",
"name": "global_uncaught_exceptions",
"meta": {
"changes": [
{
"version": "v12.3.0",
"pr-url": "https://github.com/nodejs/node/pull/27151",
"description": "The `'uncaughtException'` event is from now on triggered if the repl is used as standalone program."
}
]
},
"desc": "The REPL uses the domain
module to catch all uncaught exceptions for that\nREPL session.
This use of the domain
module in the REPL has these side effects:
'uncaughtException'
event in the\nstandalone REPL. Adding a listener for this event in a REPL within\nanother Node.js program throws ERR_INVALID_REPL_INPUT
.process.setUncaughtExceptionCaptureCallback()
throws\nan ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE
error.As standalone program:
\nprocess.on('uncaughtException', () => console.log('Uncaught'));\n\nthrow new Error('foobar');\n// Uncaught\n
\nWhen used in another application:
\nprocess.on('uncaughtException', () => console.log('Uncaught'));\n// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n// cannot be used in the REPL\n\nthrow new Error('foobar');\n// Thrown:\n// Error: foobar\n
",
"type": "module",
"displayName": "Global Uncaught Exceptions"
},
{
"textRaw": "Assignment of the `_` (underscore) variable",
"name": "assignment_of_the_`_`_(underscore)_variable",
"meta": {
"changes": [
{
"version": "v9.8.0",
"pr-url": "https://github.com/nodejs/node/pull/18919",
"description": "Added `_error` support."
}
]
},
"desc": "The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable _
(underscore).\nExplicitly setting _
to a value will disable this behavior.
> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4\n
\nSimilarly, _error
will refer to the last seen error, if there was any.\nExplicitly setting _error
to a value will disable this behavior.
> throw new Error('foo');\nError: foo\n> _error.message\n'foo'\n
",
"type": "module",
"displayName": "Assignment of the `_` (underscore) variable"
},
{
"textRaw": "`await` keyword",
"name": "`await`_keyword",
"desc": "With the --experimental-repl-await
command line option specified,\nexperimental support for the await
keyword is enabled.
> await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nError: REPL await\n at repl:1:45\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined\n
",
"type": "module",
"displayName": "`await` keyword"
}
],
"type": "module",
"displayName": "Default Evaluation"
},
{
"textRaw": "Custom Evaluation Functions",
"name": "custom_evaluation_functions",
"desc": "When a new repl.REPLServer
is created, a custom evaluation function may be\nprovided. This can be used, for instance, to implement fully customized REPL\napplications.
The following illustrates a hypothetical example of a REPL that performs\ntranslation of text from one language to another:
\nconst repl = require('repl');\nconst { Translator } = require('translator');\n\nconst myTranslator = new Translator('en', 'fr');\n\nfunction myEval(cmd, context, filename, callback) {\n callback(null, myTranslator.translate(cmd));\n}\n\nrepl.start({ prompt: '> ', eval: myEval });\n
",
"modules": [
{
"textRaw": "Recoverable Errors",
"name": "recoverable_errors",
"desc": "As a user is typing input into the REPL prompt, pressing the <enter>
key will\nsend the current line of input to the eval
function. In order to support\nmulti-line input, the eval function can return an instance of repl.Recoverable
\nto the provided callback function:
function myEval(cmd, context, filename, callback) {\n let result;\n try {\n result = vm.runInThisContext(cmd);\n } catch (e) {\n if (isRecoverableError(e)) {\n return callback(new repl.Recoverable(e));\n }\n }\n callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n if (error.name === 'SyntaxError') {\n return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n }\n return false;\n}\n
",
"type": "module",
"displayName": "Recoverable Errors"
}
],
"type": "module",
"displayName": "Custom Evaluation Functions"
},
{
"textRaw": "Customizing REPL Output",
"name": "customizing_repl_output",
"desc": "By default, repl.REPLServer
instances format output using the\nutil.inspect()
method before writing the output to the provided Writable
\nstream (process.stdout
by default). The showProxy
inspection option is set\nto true by default and the colors
option is set to true depending on the\nREPL's useColors
option.
The useColors
boolean option can be specified at construction to instruct the\ndefault writer to use ANSI style codes to colorize the output from the\nutil.inspect()
method.
If the REPL is run as standalone program, it is also possible to change the\nREPL's inspection defaults from inside the REPL by using the\ninspect.replDefaults
property which mirrors the defaultOptions
from\nutil.inspect()
.
> util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n 1\n]\n>\n
\nTo fully customize the output of a repl.REPLServer
instance pass in a new\nfunction for the writer
option on construction. The following example, for\ninstance, simply converts any input text to upper case:
const repl = require('repl');\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n callback(null, cmd);\n}\n\nfunction myWriter(output) {\n return output.toUpperCase();\n}\n
",
"type": "module",
"displayName": "Customizing REPL Output"
}
],
"type": "module",
"displayName": "Design and Features"
},
{
"textRaw": "Class: `REPLServer`",
"name": "class:_`replserver`",
"meta": {
"added": [
"v0.1.91"
],
"changes": []
},
"desc": "options
<Object> | <string> See repl.start()
Instances of repl.REPLServer
are created using the repl.start()
method\nor directly using the JavaScript new
keyword.
const repl = require('repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n
",
"modules": [
{
"textRaw": "Event: `'exit'`",
"name": "event:_`'exit'`",
"meta": {
"added": [
"v0.7.7"
],
"changes": []
},
"desc": "The 'exit'
event is emitted when the REPL is exited either by receiving the\n.exit
command as input, the user pressing <ctrl>-C
twice to signal SIGINT
,\nor by pressing <ctrl>-D
to signal 'end'
on the input stream. The listener\ncallback is invoked without any arguments.
replServer.on('exit', () => {\n console.log('Received \"exit\" event from repl!');\n process.exit();\n});\n
",
"type": "module",
"displayName": "Event: `'exit'`"
},
{
"textRaw": "Event: `'reset'`",
"name": "event:_`'reset'`",
"meta": {
"added": [
"v0.11.0"
],
"changes": []
},
"desc": "The 'reset'
event is emitted when the REPL's context is reset. This occurs\nwhenever the .clear
command is received as input unless the REPL is using\nthe default evaluator and the repl.REPLServer
instance was created with the\nuseGlobal
option set to true
. The listener callback will be called with a\nreference to the context
object as the only argument.
This can be used primarily to re-initialize REPL context to some pre-defined\nstate:
\nconst repl = require('repl');\n\nfunction initializeContext(context) {\n context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n
\nWhen this code is executed, the global 'm'
variable can be modified but then\nreset to its initial value using the .clear
command:
$ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n
",
"type": "module",
"displayName": "Event: `'reset'`"
},
{
"textRaw": "`replServer.defineCommand(keyword, cmd)`",
"name": "`replserver.definecommand(keyword,_cmd)`",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"desc": "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\nto the REPL instance. Such commands are invoked by typing a .
followed by the\nkeyword
. The cmd
is either a Function
or an Object
with the following\nproperties:
help
<string> Help text to be displayed when .help
is entered (Optional).action
<Function> The function to execute, optionally accepting a single\nstring argument.The following example shows two new commands added to the REPL instance:
\nconst repl = require('repl');\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n help: 'Say hello',\n action(name) {\n this.clearBufferedCommand();\n console.log(`Hello, ${name}!`);\n this.displayPrompt();\n }\n});\nreplServer.defineCommand('saybye', function saybye() {\n console.log('Goodbye!');\n this.close();\n});\n
\nThe new commands can then be used from within the REPL instance:
\n> .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n
",
"type": "module",
"displayName": "`replServer.defineCommand(keyword, cmd)`"
},
{
"textRaw": "`replServer.displayPrompt([preserveCursor])`",
"name": "`replserver.displayprompt([preservecursor])`",
"meta": {
"added": [
"v0.1.91"
],
"changes": []
},
"desc": "preserveCursor
<boolean>The replServer.displayPrompt()
method readies the REPL instance for input\nfrom the user, printing the configured prompt
to a new line in the output
\nand resuming the input
to accept new input.
When multi-line input is being entered, an ellipsis is printed rather than the\n'prompt'.
\nWhen preserveCursor
is true
, the cursor placement will not be reset to 0
.
The replServer.displayPrompt
method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand()
method.
The replServer.clearBufferedCommand()
method clears any command that has been\nbuffered but not yet executed. This method is primarily intended to be\ncalled from within the action function for commands registered using the\nreplServer.defineCommand()
method.
keyword
<string> the potential keyword to parse and executerest
<any> any parameters to the keyword commandAn internal method used to parse and execute REPLServer
keywords.\nReturns true
if keyword
is a valid keyword, otherwise false
.
historyPath
<string> the path to the history filecallback
<Function> called when history writes are ready or upon error
err
<Error>repl
<repl.REPLServer>Initializes a history log file for the REPL instance. When executing the\nNode.js binary and using the command line REPL, a history file is initialized\nby default. However, this is not the case when creating a REPL\nprogrammatically. Use this method to initialize a history log file when working\nwith REPL instances programmatically.
", "type": "module", "displayName": "`replServer.setupHistory(historyPath, callback)`" } ], "type": "module", "displayName": "Class: `REPLServer`" }, { "textRaw": "`repl.start([options])`", "name": "`repl.start([options])`", "meta": { "added": [ "v0.1.91" ], "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26518", "description": "The `terminal` option now follows the default description in all cases and `useColors` checks `hasColors()` if available." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19187", "description": "The `REPL_MAGIC_MODE` `replMode` was removed." }, { "version": "v5.8.0", "pr-url": "https://github.com/nodejs/node/pull/5388", "description": "The `options` parameter is optional now." } ] }, "desc": "prompt
<string> The input prompt to display. Default: '> '
\n(with a trailing space).input
<stream.Readable> The Readable
stream from which REPL input will\nbe read. Default: process.stdin
.output
<stream.Writable> The Writable
stream to which REPL output will\nbe written. Default: process.stdout
.terminal
<boolean> If true
, specifies that the output
should be\ntreated as a TTY terminal.\nDefault: checking the value of the isTTY
property on the output
\nstream upon instantiation.eval
<Function> The function to be used when evaluating each given line\nof input. Default: an async wrapper for the JavaScript eval()
\nfunction. An eval
function can error with repl.Recoverable
to indicate\nthe input was incomplete and prompt for additional lines.useColors
<boolean> If true
, specifies that the default writer
\nfunction should include ANSI color styling to REPL output. If a custom\nwriter
function is provided then this has no effect. Default: checking\ncolor support on the output
stream if the REPL instance's terminal
value\nis true
.useGlobal
<boolean> If true
, specifies that the default evaluation\nfunction will use the JavaScript global
as the context as opposed to\ncreating a new separate context for the REPL instance. The node CLI REPL\nsets this value to true
. Default: false
.ignoreUndefined
<boolean> If true
, specifies that the default writer\nwill not output the return value of a command if it evaluates to\nundefined
. Default: false
.writer
<Function> The function to invoke to format the output of each\n command before writing to output
. Default: util.inspect()
.completer
<Function> An optional function used for custom Tab auto\n completion. See readline.InterfaceCompleter
for an example.replMode
<symbol> A flag that specifies whether the default evaluator\nexecutes all JavaScript commands in strict mode or default (sloppy) mode.\nAcceptable values are:
repl.REPL_MODE_SLOPPY
to evaluate expressions in sloppy mode.repl.REPL_MODE_STRICT
to evaluate expressions in strict mode. This is\nequivalent to prefacing every repl statement with 'use strict'
.breakEvalOnSigint
<boolean> Stop evaluating the current piece of code when\nSIGINT
is received, such as when Ctrl+C
is pressed. This cannot be used\ntogether with a custom eval
function. Default: false
.The repl.start()
method creates and starts a repl.REPLServer
instance.
If options
is a string, then it specifies the input prompt:
const repl = require('repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n
",
"type": "module",
"displayName": "`repl.start([options])`"
},
{
"textRaw": "The Node.js REPL",
"name": "the_node.js_repl",
"desc": "Node.js itself uses the repl
module to provide its own interactive interface\nfor executing JavaScript. This can be used by executing the Node.js binary\nwithout passing any arguments (or by passing the -i
argument):
$ node\n> const a = [1, 2, 3];\nundefined\n> a\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n... console.log(v);\n... });\n1\n2\n3\n
",
"modules": [
{
"textRaw": "Environment Variable Options",
"name": "environment_variable_options",
"desc": "Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:
\nNODE_REPL_HISTORY
: When a valid path is given, persistent REPL history\nwill be saved to the specified file rather than .node_repl_history
in the\nuser's home directory. Setting this value to ''
(an empty string) will\ndisable persistent REPL history. Whitespace will be trimmed from the value.\nOn Windows platforms environment variables with empty values are invalid so\nset this variable to one or more spaces to disable persistent REPL history.NODE_REPL_HISTORY_SIZE
: Controls how many lines of history will be\npersisted if history is available. Must be a positive number.\nDefault: 1000
.NODE_REPL_MODE
: May be either 'sloppy'
or 'strict'
. Default:\n'sloppy'
, which will allow non-strict mode code to be run.By default, the Node.js REPL will persist history between node
REPL sessions\nby saving inputs to a .node_repl_history
file located in the user's home\ndirectory. This can be disabled by setting the environment variable\nNODE_REPL_HISTORY=''
.
For advanced line-editors, start Node.js with the environment variable\nNODE_NO_READLINE=1
. This will start the main and debugger REPL in canonical\nterminal 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\"\n
",
"type": "module",
"displayName": "Using the Node.js REPL with advanced line-editors"
},
{
"textRaw": "Starting multiple REPL instances against a single running instance",
"name": "starting_multiple_repl_instances_against_a_single_running_instance",
"desc": "It is possible to create and run multiple REPL instances against a single\nrunning instance of Node.js that share a single global
object but have\nseparate I/O interfaces.
The following example, for instance, provides separate REPLs on stdin
, a Unix\nsocket, and a TCP socket:
const net = require('net');\nconst repl = require('repl');\nlet connections = 0;\n\nrepl.start({\n prompt: 'Node.js via stdin> ',\n input: process.stdin,\n output: process.stdout\n});\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via Unix socket> ',\n input: socket,\n output: socket\n }).on('exit', () => {\n socket.end();\n });\n}).listen('/tmp/node-repl-sock');\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via TCP socket> ',\n input: socket,\n output: socket\n }).on('exit', () => {\n socket.end();\n });\n}).listen(5001);\n
\nRunning this application from the command line will start a REPL on stdin.\nOther REPL clients may connect through the Unix socket or TCP socket. telnet
,\nfor instance, is useful for connecting to TCP sockets, while socat
can be used\nto connect to both Unix and TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, it is\npossible to connect to a long-running Node.js process without restarting it.
\nFor an example of running a \"full-featured\" (terminal
) REPL over\na net.Server
and net.Socket
instance, see:\nhttps://gist.github.com/TooTallNate/2209310.
For an example of running a REPL instance over curl(1)
, see:\nhttps://gist.github.com/TooTallNate/2053342.