Source Code: lib/repl.js
The node:repl module provides a Read-Eval-Print-Loop (REPL) implementation\nthat is available both as a standalone program or includible in other\napplications. It can be accessed using:
node:repl
const repl = require('node:repl');\n
The node: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.
repl.REPLServer
stdin
stdout
Instances of repl.REPLServer support automatic completion of inputs,\ncompletion preview, simplistic Emacs-style line editing, multi-line inputs,\nZSH-like reverse-i-search, ZSH-like substring-based history search,\nANSI-styled output, saving and restoring current REPL session state, error\nrecovery, and customizable evaluation functions. Terminals that do not support\nANSI styles and Emacs-style line editing automatically fall back to a limited\nfeature set.
The following special commands are supported by all REPL instances:
.break
.clear
context
.exit
.help
.save
> .save ./file/to/save.js
.load
> .load ./file/to/load.js
.editor
> .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
The following key combinations in the REPL have these special effects:
For key bindings related to the reverse-i-search, see reverse-i-search.\nFor all other key bindings, see TTY keybindings.
reverse-i-search
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:
> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n
Unless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const, let, or var keywords\nare declared at the global scope.
const
let
var
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:
REPLServer
const repl = require('node:repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n
Properties in the context object appear as local within the REPL:
$ node repl_test.js\n> m\n'message'\n
Context properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using Object.defineProperty():
Object.defineProperty()
const repl = require('node: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
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('node:fs').
fs
global.fs = require('node:fs')
> fs.createReadStream('./some/file');\n
The REPL uses the domain module to catch all uncaught exceptions for that\nREPL session.
domain
This use of the domain module in the REPL has these side effects:
Uncaught exceptions only emit the 'uncaughtException' event in the\nstandalone REPL. Adding a listener for this event in a REPL within\nanother Node.js program results in ERR_INVALID_REPL_INPUT.
'uncaughtException'
ERR_INVALID_REPL_INPUT
const r = repl.start();\n\nr.write('process.on(\"uncaughtException\", () => console.log(\"Foobar\"));\\n');\n// Output stream includes:\n// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n// cannot be used in the REPL\n\nr.close();\n
Trying to use process.setUncaughtExceptionCaptureCallback() throws\nan ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE error.
process.setUncaughtExceptionCaptureCallback()
ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE
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
Similarly, _error will refer to the last seen error, if there was any.\nExplicitly setting _error to a value will disable this behavior.
_error
> throw new Error('foo');\nError: foo\n> _error.message\n'foo'\n
Support for the await keyword is enabled at the top level.
await
> 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
One known limitation of using the await keyword in the REPL is that\nit will invalidate the lexical scoping of the const and let\nkeywords.
For example:
> const m = await Promise.resolve(123)\nundefined\n> m\n123\n> const m = await Promise.resolve(234)\nundefined\n> m\n234\n
--no-experimental-repl-await shall disable top-level await in REPL.
--no-experimental-repl-await
The REPL supports bi-directional reverse-i-search similar to ZSH. It is\ntriggered with Ctrl+R to search backward\nand 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\nwith the reverse search. Cancelling is possible by pressing Esc\nor Ctrl+C.
Changing the direction immediately searches for the next entry in the expected\ndirection from the current position on.
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:
const repl = require('node: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
At the REPL prompt, pressing Enter sends the current line of input to\nthe eval function. In order to support multi-line input, the eval function\ncan return an instance of repl.Recoverable to the provided callback function:
eval
repl.Recoverable
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
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.
util.inspect()
Writable
process.stdout
showProxy
colors
useColors
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().
inspect.replDefaults
defaultOptions
> util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n 1\n]\n>\n
To 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:
writer
const repl = require('node: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
Node.js itself uses the node:repl module to provide its own interactive\ninterface for executing JavaScript. This can be used by executing the Node.js\nbinary without passing any arguments (or by passing the -i argument):
-i
$ 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
Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:
NODE_REPL_HISTORY
.node_repl_history
''
NODE_REPL_HISTORY_SIZE
1000
NODE_REPL_MODE
'sloppy'
'strict'
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=''.
node
NODE_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.
NODE_NO_READLINE=1
rlwrap
For example, the following can be added to a .bashrc file:
.bashrc
alias node=\"env NODE_NO_READLINE=1 rlwrap node\"\n
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.
global
The following example, for instance, provides separate REPLs on stdin, a Unix\nsocket, and a TCP socket:
const net = require('node:net');\nconst repl = require('node: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
Running 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.
telnet
socat
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.
For an example of running a \"full-featured\" (terminal) REPL over\na net.Server and net.Socket instance, see:\nhttps://gist.github.com/TooTallNate/2209310.
terminal
net.Server
net.Socket
For an example of running a REPL instance over curl(1), see:\nhttps://gist.github.com/TooTallNate/2053342.
curl(1)
options
repl.start()
Instances of repl.REPLServer are created using the repl.start() method\nor directly using the JavaScript new keyword.
new
const repl = require('node:repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n
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\nto signal SIGINT,\nor by pressing Ctrl+D to signal 'end' on the input\nstream. The listener\ncallback is invoked without any arguments.
'exit'
SIGINT
'end'
replServer.on('exit', () => {\n console.log('Received \"exit\" event from repl!');\n process.exit();\n});\n
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.
'reset'
useGlobal
true
This can be used primarily to re-initialize REPL context to some pre-defined\nstate:
const repl = require('node: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
When this code is executed, the global 'm' variable can be modified but then\nreset to its initial value using the .clear command:
'm'
$ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n
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:
replServer.defineCommand()
.
keyword
cmd
Function
Object
help
action
The following example shows two new commands added to the REPL instance:
const repl = require('node: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
The new commands can then be used from within the REPL instance:
> .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n
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.
replServer.displayPrompt()
prompt
output
input
When multi-line input is being entered, an ellipsis is printed rather than the\n'prompt'.
When preserveCursor is true, the cursor placement will not be reset to 0.
preserveCursor
0
The replServer.displayPrompt method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand() method.
replServer.displayPrompt
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.
replServer.clearBufferedCommand()
An internal method used to parse and execute REPLServer keywords.\nReturns true if keyword is a valid keyword, otherwise false.
false
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.
A list of the names of all Node.js modules, e.g., 'http'.
'http'
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('node:repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n