doc: sort repl alphabetically
[platform/upstream/nodejs.git] / doc / api / repl.markdown
1 # REPL
2
3     Stability: 2 - Stable
4
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.
9
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.
12
13     mjr:~$ node
14     Type '.help' for options.
15     > a = [ 1, 2, 3];
16     [ 1, 2, 3 ]
17     > a.forEach(function (v) {
18     ...   console.log(v);
19     ...   });
20     1
21     2
22     3
23
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`.
27
28 For example, you could add this to your bashrc file:
29
30     alias node="env NODE_NO_READLINE=1 rlwrap node"
31
32 ## Environment Variable Options
33
34 The built-in repl (invoked by running `node` or `node -i`) may be controlled
35 via the following environment variables:
36
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.
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
45    strict mode.
46
47 ## Persistent History
48
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=""`.
52
53 ### NODE_REPL_HISTORY_FILE
54
55     Stability: 0 - Deprecated: Use `NODE_REPL_HISTORY` instead.
56
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 below.
63
64 ## REPL Features
65
66 <!-- type=misc -->
67
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.
70
71 Core modules will be loaded on-demand into the environment. For example,
72 accessing `fs` will `require()` the `fs` module as `global.fs`.
73
74 The special variable `_` (underscore) contains the result of the last expression.
75
76     > [ 'a', 'b', 'c' ]
77     [ 'a', 'b', 'c' ]
78     > _.length
79     3
80     > _ += 1
81     4
82
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:
86
87     // repl_test.js
88     var repl = require('repl'),
89         msg = 'message';
90
91     repl.start('> ').context.m = msg;
92
93 Things in the `context` object appear as local within the REPL:
94
95     mjr:~$ node repl_test.js
96     > m
97     'message'
98
99 There are a few special REPL commands:
100
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
111
112 The following key combinations in the REPL have these special effects:
113
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
118
119
120 ### Customizing Object displays in the REPL
121
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][].
126
127 For example, if you have defined an `inspect()` function on an object, like this:
128
129     > var obj = { foo: 'this will not show up in the inspect() output' };
130     undefined
131     > obj.inspect = function() {
132     ...   return { bar: 'baz' };
133     ... };
134     [Function]
135
136 and try to print `obj` in REPL, it will invoke the custom `inspect()` function:
137
138     > obj
139     { bar: 'baz' }
140
141 ## Class: REPLServer
142
143 This inherits from [Readline Interface][] with the following events:
144
145 ### Event: 'exit'
146
147 `function () {}`
148
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.
152
153 Example of listening for `exit`:
154
155     replServer.on('exit', function () {
156       console.log('Got "exit" event from repl!');
157       process.exit();
158     });
159
160
161 ### Event: 'reset'
162
163 `function (context) {}`
164
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
167 be emitted.
168
169 Example of listening for `reset`:
170
171     // Extend the initial repl context.
172     var replServer = repl.start({ options ... });
173     someExtension.extend(r.context);
174
175     // When a new context is created extend it as well.
176     replServer.on('reset', function (context) {
177       console.log('repl has a new context');
178       someExtension.extend(context);
179     });
180
181 ### replServer.defineCommand(keyword, cmd)
182
183 * `keyword` {String}
184 * `cmd` {Object|Function}
185
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:
188
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).
192
193 If a function is provided instead of an object for `cmd`, it is treated as the
194 `action`.
195
196 Example of defining a command:
197
198     // repl_test.js
199     var repl = require('repl');
200
201     var replServer = repl.start();
202     replServer.defineCommand('sayhello', {
203       help: 'Say hello',
204       action: function(name) {
205         this.write('Hello, ' + name + '!\n');
206         this.displayPrompt();
207       }
208     });
209
210 Example of invoking that command from the REPL:
211
212     > .sayhello Node.js User
213     Hello, Node.js User!
214
215 ### replServer.displayPrompt([preserveCursor])
216
217 * `preserveCursor` {Boolean}
218
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
222 prompt line.
223
224 ## repl.start(options)
225
226 Returns and starts a `REPLServer` instance, that inherits from
227 [Readline Interface][]. Accepts an "options" Object that takes
228 the following values:
229
230  - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `.
231
232  - `input` - the readable stream to listen to. Defaults to `process.stdin`.
233
234  - `output` - the writable stream to write readline data to. Defaults to
235    `process.stdout`.
236
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.
240
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`.
243
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.
247
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`.
250
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`.
253
254  - `writer` - the function to invoke for each command that gets evaluated which
255    returns the formatting (including coloring) to display. Defaults to
256    `util.inspect`.
257
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.
265
266 You can use your own `eval` function if it has following signature:
267
268     function eval(cmd, context, filename, callback) {
269       callback(null, result);
270     }
271
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.
274
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.
277
278 Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
279
280     var net = require('net'),
281         repl = require('repl'),
282         connections = 0;
283
284     repl.start({
285       prompt: 'Node.js via stdin> ',
286       input: process.stdin,
287       output: process.stdout
288     });
289
290     net.createServer(function (socket) {
291       connections += 1;
292       repl.start({
293         prompt: 'Node.js via Unix socket> ',
294         input: socket,
295         output: socket
296       }).on('exit', function() {
297         socket.end();
298       })
299     }).listen('/tmp/node-repl-sock');
300
301     net.createServer(function (socket) {
302       connections += 1;
303       repl.start({
304         prompt: 'Node.js via TCP socket> ',
305         input: socket,
306         output: socket
307       }).on('exit', function() {
308         socket.end();
309       });
310     }).listen(5001);
311
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
315 TCP sockets.
316
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.
319
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
322
323 For an example of running a REPL instance over `curl(1)`,
324 see: https://gist.github.com/2053342
325
326 [Readline Interface]: readline.html#readline_class_interface
327 [readline.prompt]: readline.html#readline_rl_prompt_preservecursor
328 [util.inspect()]: util.html#util_util_inspect_object_options
329 [here]: util.html#util_custom_inspect_function_on_objects