{ "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
\n",
"modules": [
{
"textRaw": "Design and Features",
"name": "design_and_features",
"desc": "The repl
module exports the repl.REPLServer
class. While running, instances\nof repl.REPLServer
will accept individual lines of user input, evaluate those\naccording to a user-defined evaluation function, then output the result. Input\nand output may be from stdin
and stdout
, respectively, or may be connected\nto 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 that\nevaluates 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\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
\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
\n",
"type": "module",
"displayName": "Accessing Core Node.js Modules"
},
{
"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
\n",
"type": "module",
"displayName": "Assignment of the `_` (underscore) variable"
}
],
"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
\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
\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 useColors
boolean option can be\nspecified at construction to instruct the default writer to use ANSI style\ncodes to colorize the output from the util.inspect()
method.
It is possible to fully customize the output of a repl.REPLServer
instance\nby passing a new function in using the writer
option on construction. The\nfollowing example, for instance, 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
\n",
"type": "module",
"displayName": "Customizing REPL Output"
}
],
"type": "module",
"displayName": "Design and Features"
},
{
"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
\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 ''
will disable persistent\nREPL history. Whitespace will be trimmed from the value.NODE_REPL_HISTORY_SIZE
- Defaults to 1000
. Controls how many lines of\nhistory will be persisted if history is available. Must be a positive number.NODE_REPL_MODE
- May be any of sloppy
, strict
, or magic
. Defaults\nto sloppy
, which will allow non-strict mode code to be run. magic
is\ndeprecated and treated as an alias of sloppy
.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=''
.
Previously in Node.js/io.js v2.x, REPL history was controlled by using a\nNODE_REPL_HISTORY_FILE
environment variable, and the history was saved in JSON\nformat. This variable has now been deprecated, and the old JSON REPL history\nfile will be automatically converted to a simplified plain text format. This new\nfile will be saved to either the user's home directory, or a directory defined\nby the NODE_REPL_HISTORY
variable, as documented in the\nEnvironment Variable Options.
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
\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: https://gist.github.com/2209310
For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342
\n", "type": "module", "displayName": "Starting multiple REPL instances against a single running instance" } ], "type": "module", "displayName": "The Node.js REPL" } ], "classes": [ { "textRaw": "Class: REPLServer", "type": "class", "name": "REPLServer", "meta": { "added": [ "v0.1.91" ], "changes": [] }, "desc": "The repl.REPLServer
class inherits from the readline.Interface
class.\nInstances of repl.REPLServer
are created using the repl.start()
method and\nshould not be created directly using the JavaScript new
keyword.
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
\n",
"params": []
},
{
"textRaw": "Event: 'reset'",
"type": "event",
"name": "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 as illustrated in the following simple example:
\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
\n",
"params": []
}
],
"methods": [
{
"textRaw": "replServer.defineCommand(keyword, cmd)",
"type": "method",
"name": "defineCommand",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`keyword` {string} The command keyword (*without* a leading `.` character). ",
"name": "keyword",
"type": "string",
"desc": "The command keyword (*without* a leading `.` character)."
},
{
"textRaw": "`cmd` {Object|Function} The function to invoke when the command is processed. ",
"name": "cmd",
"type": "Object|Function",
"desc": "The function to invoke when the command is processed."
}
]
},
{
"params": [
{
"name": "keyword"
},
{
"name": "cmd"
}
]
}
],
"desc": "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
\n"
},
{
"textRaw": "replServer.displayPrompt([preserveCursor])",
"type": "method",
"name": "displayPrompt",
"meta": {
"added": [
"v0.1.91"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`preserveCursor` {boolean} ",
"name": "preserveCursor",
"type": "boolean",
"optional": true
}
]
},
{
"params": [
{
"name": "preserveCursor",
"optional": true
}
]
}
],
"desc": "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.
An internal method used to parse and execute REPLServer
keywords.\nReturns true
if keyword
is a valid keyword, otherwise 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
\n"
}
],
"type": "module",
"displayName": "REPL"
}
]
}