5 A Read-Eval-Print-Loop (REPL) is available both as a standalone program and
6 easily includable in other programs. The REPL provides a way to interactively
7 run JavaScript and see the results. It can be used for debugging, testing, or
8 just trying things out.
10 By executing `node` without any arguments from the command-line you will be
11 dropped into the REPL. It has simplistic emacs line-editing.
14 Type '.help' for options.
17 > a.forEach(function (v) {
24 For advanced line-editors, start Node.js with the environmental variable
25 `NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical
26 terminal settings which will allow you to use with `rlwrap`.
28 For example, you could add this to your bashrc file:
30 alias node="env NODE_NO_READLINE=1 rlwrap node"
32 ## Environment Variable Options
34 The built-in repl (invoked by running `node` or `node -i`) may be controlled
35 via the following environment variables:
37 - `NODE_REPL_HISTORY` - When a valid path is given, persistent REPL history
38 will be saved to the specified file rather than `.node_repl_history` in the
39 user's home directory. Setting this value to `""` will disable persistent
40 REPL history. Whitespace will be trimmed from the value.
41 - `NODE_REPL_HISTORY_SIZE` - Defaults to `1000`. Controls how many lines of
42 history will be persisted if history is available. Must be a positive number.
43 - `NODE_REPL_MODE` - May be any of `sloppy`, `strict`, or `magic`. Defaults
44 to `magic`, which will automatically run "strict mode only" statements in
49 By default, the REPL will persist history between `node` REPL sessions by saving
50 to a `.node_repl_history` file in the user's home directory. This can be
51 disabled by setting the environment variable `NODE_REPL_HISTORY=""`.
53 ### NODE_REPL_HISTORY_FILE
55 Stability: 0 - Deprecated: Use `NODE_REPL_HISTORY` instead.
57 Previously in Node.js/io.js v2.x, REPL history was controlled by using a
58 `NODE_REPL_HISTORY_FILE` environment variable, and the history was saved in JSON
59 format. This variable has now been deprecated, and your REPL history will
60 automatically be converted to using plain text. The new file will be saved to
61 either your home directory, or a directory defined by the `NODE_REPL_HISTORY`
62 variable, as documented [here](#repl_environment_variable_options).
68 Inside the REPL, Control+D will exit. Multi-line expressions can be input.
69 Tab completion is supported for both global and local variables.
71 Core modules will be loaded on-demand into the environment. For example,
72 accessing `fs` will `require()` the `fs` module as `global.fs`.
74 The special variable `_` (underscore) contains the result of the last expression.
83 The REPL provides access to any variables in the global scope. You can expose
84 a variable to the REPL explicitly by assigning it to the `context` object
85 associated with each `REPLServer`. For example:
88 const repl = require('repl');
91 repl.start('> ').context.m = msg;
93 Things in the `context` object appear as local within the REPL:
95 mjr:~$ node repl_test.js
99 There are a few special REPL commands:
101 - `.break` - While inputting a multi-line expression, sometimes you get lost
102 or just don't care about completing it. `.break` will start over.
103 - `.clear` - Resets the `context` object to an empty object and clears any
104 multi-line expression.
105 - `.exit` - Close the I/O stream, which will cause the REPL to exit.
106 - `.help` - Show this list of special commands.
107 - `.save` - Save the current REPL session to a file
108 >.save ./file/to/save.js
109 - `.load` - Load a file into the current REPL session.
110 >.load ./file/to/load.js
112 The following key combinations in the REPL have these special effects:
114 - `<ctrl>C` - Similar to the `.break` keyword. Terminates the current
115 command. Press twice on a blank line to forcibly exit.
116 - `<ctrl>D` - Similar to the `.exit` keyword.
117 - `<tab>` - Show both global and local(scope) variables
120 ### Customizing Object displays in the REPL
122 The REPL module internally uses
123 [`util.inspect()`][], when printing values. However, `util.inspect` delegates the
124 call to the object's `inspect()` function, if it has one. You can read more
125 about this delegation [here][].
127 For example, if you have defined an `inspect()` function on an object, like this:
129 > var obj = { foo: 'this will not show up in the inspect() output' };
131 > obj.inspect = function() {
132 ... return { bar: 'baz' };
136 and try to print `obj` in REPL, it will invoke the custom `inspect()` function:
143 This inherits from [Readline Interface][] with the following events:
149 Emitted when the user exits the REPL in any of the defined ways. Namely, typing
150 `.exit` at the repl, pressing Ctrl+C twice to signal `SIGINT`, or pressing Ctrl+D
151 to signal `'end'` on the `input` stream.
153 Example of listening for `exit`:
155 replServer.on('exit', () => {
156 console.log('Got "exit" event from repl!');
163 `function (context) {}`
165 Emitted when the REPL's context is reset. This happens when you type `.clear`.
166 If you start the repl with `{ useGlobal: true }` then this event will never
169 Example of listening for `reset`:
171 // Extend the initial repl context.
172 var replServer = repl.start({ options ... });
173 someExtension.extend(r.context);
175 // When a new context is created extend it as well.
176 replServer.on('reset', (context) => {
177 console.log('repl has a new context');
178 someExtension.extend(context);
181 ### replServer.defineCommand(keyword, cmd)
184 * `cmd` {Object|Function}
186 Makes a command available in the REPL. The command is invoked by typing a `.`
187 followed by the keyword. The `cmd` is an object with the following values:
189 - `help` - help text to be displayed when `.help` is entered (Optional).
190 - `action` - a function to execute, potentially taking in a string argument,
191 when the command is invoked, bound to the REPLServer instance (Required).
193 If a function is provided instead of an object for `cmd`, it is treated as the
196 Example of defining a command:
199 const repl = require('repl');
201 var replServer = repl.start();
202 replServer.defineCommand('sayhello', {
204 action: function(name) {
205 this.write(`Hello, ${name}!\n');
206 this.displayPrompt();
210 Example of invoking that command from the REPL:
212 > .sayhello Node.js User
215 ### replServer.displayPrompt([preserveCursor])
217 * `preserveCursor` {Boolean}
219 Like [`readline.prompt`][] except also adding indents with ellipses when inside
220 blocks. The `preserveCursor` argument is passed to [`readline.prompt`][]. This is
221 used primarily with `defineCommand`. It's also used internally to render each
224 ## repl.start(options)
226 Returns and starts a `REPLServer` instance, that inherits from
227 [Readline Interface][]. Accepts an "options" Object that takes
228 the following values:
230 - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `.
232 - `input` - the readable stream to listen to. Defaults to `process.stdin`.
234 - `output` - the writable stream to write readline data to. Defaults to
237 - `terminal` - pass `true` if the `stream` should be treated like a TTY, and
238 have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY`
239 on the `output` stream upon instantiation.
241 - `eval` - function that will be used to eval each given line. Defaults to
242 an async wrapper for `eval()`. See below for an example of a custom `eval`.
244 - `useColors` - a boolean which specifies whether or not the `writer` function
245 should output colors. If a different `writer` function is set then this does
246 nothing. Defaults to the repl's `terminal` value.
248 - `useGlobal` - if set to `true`, then the repl will use the `global` object,
249 instead of running scripts in a separate context. Defaults to `false`.
251 - `ignoreUndefined` - if set to `true`, then the repl will not output the
252 return value of command if it's `undefined`. Defaults to `false`.
254 - `writer` - the function to invoke for each command that gets evaluated which
255 returns the formatting (including coloring) to display. Defaults to
258 - `replMode` - controls whether the repl runs all commands in strict mode,
259 default mode, or a hybrid mode ("magic" mode.) Acceptable values are:
260 * `repl.REPL_MODE_SLOPPY` - run commands in sloppy mode.
261 * `repl.REPL_MODE_STRICT` - run commands in strict mode. This is equivalent to
262 prefacing every repl statement with `'use strict'`.
263 * `repl.REPL_MODE_MAGIC` - attempt to run commands in default mode. If they
264 fail to parse, re-try in strict mode.
266 You can use your own `eval` function if it has following signature:
268 function eval(cmd, context, filename, callback) {
269 callback(null, result);
272 On tab completion, `eval` will be called with `.scope` as an input string. It
273 is expected to return an array of scope names to be used for the auto-completion.
275 Multiple REPLs may be started against the same running instance of Node.js. Each
276 will share the same global object but will have unique I/O.
278 Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
280 const net = require('net');
281 const repl = require('repl');
285 prompt: 'Node.js via stdin> ',
286 input: process.stdin,
287 output: process.stdout
290 net.createServer((socket) => {
293 prompt: 'Node.js via Unix socket> ',
296 }).on('exit', () => {
299 }).listen('/tmp/node-repl-sock');
301 net.createServer((socket) => {
304 prompt: 'Node.js via TCP socket> ',
307 }).on('exit', () => {
312 Running this program from the command line will start a REPL on stdin. Other
313 REPL clients may connect through the Unix socket or TCP socket. `telnet` is useful
314 for connecting to TCP sockets, and `socat` can be used to connect to both Unix and
317 By starting a REPL from a Unix socket-based server instead of stdin, you can
318 connect to a long-running Node.js process without restarting it.
320 For an example of running a "full-featured" (`terminal`) REPL over
321 a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310
323 For an example of running a REPL instance over `curl(1)`,
324 see: https://gist.github.com/2053342
326 [`readline.prompt`]: readline.html#readline_rl_prompt_preservecursor
327 [`util.inspect()`]: util.html#util_util_inspect_object_options
328 [here]: util.html#util_custom_inspect_function_on_objects
329 [Readline Interface]: readline.html#readline_class_interface