doc: fix broken link in repl.markdown
[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 ## Persistent History
33
34 By default, the REPL will persist history between `node` REPL sessions by saving
35 to a `.node_repl_history` file in the user's home directory. This can be
36 disabled by setting the environment variable `NODE_REPL_HISTORY=""`.
37
38 ### NODE_REPL_HISTORY_FILE
39
40     Stability: 0 - Deprecated: Use `NODE_REPL_HISTORY` instead.
41
42 Previously in Node.js/io.js v2.x, REPL history was controlled by using a
43 `NODE_REPL_HISTORY_FILE` environment variable, and the history was saved in JSON
44 format. This variable has now been deprecated, and your REPL history will
45 automatically be converted to using plain text. The new file will be saved to
46 either your home directory, or a directory defined by the `NODE_REPL_HISTORY`
47 variable, as documented below.
48
49 ## Environment Variable Options
50
51 The built-in repl (invoked by running `node` or `node -i`) may be controlled
52 via the following environment variables:
53
54  - `NODE_REPL_HISTORY` - When a valid path is given, persistent REPL history
55    will be saved to the specified file rather than `.node_repl_history` in the
56    user's home directory. Setting this value to `""` will disable persistent
57    REPL history.
58  - `NODE_REPL_HISTORY_SIZE` - defaults to `1000`. Controls how many lines of
59    history will be persisted if history is available. Must be a positive number.
60  - `NODE_REPL_MODE` - may be any of `sloppy`, `strict`, or `magic`. Defaults
61    to `magic`, which will automatically run "strict mode only" statements in
62    strict mode.
63
64 ## repl.start(options)
65
66 Returns and starts a `REPLServer` instance, that inherits from
67 [Readline Interface][]. Accepts an "options" Object that takes
68 the following values:
69
70  - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `.
71
72  - `input` - the readable stream to listen to. Defaults to `process.stdin`.
73
74  - `output` - the writable stream to write readline data to. Defaults to
75    `process.stdout`.
76
77  - `terminal` - pass `true` if the `stream` should be treated like a TTY, and
78    have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY`
79    on the `output` stream upon instantiation.
80
81  - `eval` - function that will be used to eval each given line. Defaults to
82    an async wrapper for `eval()`. See below for an example of a custom `eval`.
83
84  - `useColors` - a boolean which specifies whether or not the `writer` function
85    should output colors. If a different `writer` function is set then this does
86    nothing. Defaults to the repl's `terminal` value.
87
88  - `useGlobal` - if set to `true`, then the repl will use the `global` object,
89    instead of running scripts in a separate context. Defaults to `false`.
90
91  - `ignoreUndefined` - if set to `true`, then the repl will not output the
92    return value of command if it's `undefined`. Defaults to `false`.
93
94  - `writer` - the function to invoke for each command that gets evaluated which
95    returns the formatting (including coloring) to display. Defaults to
96    `util.inspect`.
97
98  - `replMode` - controls whether the repl runs all commands in strict mode,
99    default mode, or a hybrid mode ("magic" mode.) Acceptable values are:
100   * `repl.REPL_MODE_SLOPPY` - run commands in sloppy mode.
101   * `repl.REPL_MODE_STRICT` - run commands in strict mode. This is equivalent to
102   prefacing every repl statement with `'use strict'`.
103   * `repl.REPL_MODE_MAGIC` - attempt to run commands in default mode. If they
104   fail to parse, re-try in strict mode.
105
106 You can use your own `eval` function if it has following signature:
107
108     function eval(cmd, context, filename, callback) {
109       callback(null, result);
110     }
111
112 On tab completion - `eval` will be called with `.scope` as an input string. It
113 is expected to return an array of scope names to be used for the auto-completion.
114
115 Multiple REPLs may be started against the same running instance of Node.js.  Each
116 will share the same global object but will have unique I/O.
117
118 Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
119
120     var net = require('net'),
121         repl = require('repl'),
122         connections = 0;
123
124     repl.start({
125       prompt: 'Node.js via stdin> ',
126       input: process.stdin,
127       output: process.stdout
128     });
129
130     net.createServer(function (socket) {
131       connections += 1;
132       repl.start({
133         prompt: 'Node.js via Unix socket> ',
134         input: socket,
135         output: socket
136       }).on('exit', function() {
137         socket.end();
138       })
139     }).listen('/tmp/node-repl-sock');
140
141     net.createServer(function (socket) {
142       connections += 1;
143       repl.start({
144         prompt: 'Node.js via TCP socket> ',
145         input: socket,
146         output: socket
147       }).on('exit', function() {
148         socket.end();
149       });
150     }).listen(5001);
151
152 Running this program from the command line will start a REPL on stdin.  Other
153 REPL clients may connect through the Unix socket or TCP socket. `telnet` is useful
154 for connecting to TCP sockets, and `socat` can be used to connect to both Unix and
155 TCP sockets.
156
157 By starting a REPL from a Unix socket-based server instead of stdin, you can
158 connect to a long-running Node.js process without restarting it.
159
160 For an example of running a "full-featured" (`terminal`) REPL over
161 a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310
162
163 For an example of running a REPL instance over `curl(1)`,
164 see: https://gist.github.com/2053342
165
166 ### Event: 'exit'
167
168 `function () {}`
169
170 Emitted when the user exits the REPL in any of the defined ways. Namely, typing
171 `.exit` at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D
172 to signal "end" on the `input` stream.
173
174 Example of listening for `exit`:
175
176     r.on('exit', function () {
177       console.log('Got "exit" event from repl!');
178       process.exit();
179     });
180
181
182 ### Event: 'reset'
183
184 `function (context) {}`
185
186 Emitted when the REPL's context is reset. This happens when you type `.clear`.
187 If you start the repl with `{ useGlobal: true }` then this event will never
188 be emitted.
189
190 Example of listening for `reset`:
191
192     // Extend the initial repl context.
193     var r = repl.start({ options ... });
194     someExtension.extend(r.context);
195
196     // When a new context is created extend it as well.
197     r.on('reset', function (context) {
198       console.log('repl has a new context');
199       someExtension.extend(context);
200     });
201
202
203 ## REPL Features
204
205 <!-- type=misc -->
206
207 Inside the REPL, Control+D will exit.  Multi-line expressions can be input.
208 Tab completion is supported for both global and local variables.
209
210 Core modules will be loaded on-demand into the environment. For example,
211 accessing `fs` will `require()` the `fs` module as `global.fs`.
212
213 The special variable `_` (underscore) contains the result of the last expression.
214
215     > [ 'a', 'b', 'c' ]
216     [ 'a', 'b', 'c' ]
217     > _.length
218     3
219     > _ += 1
220     4
221
222 The REPL provides access to any variables in the global scope. You can expose
223 a variable to the REPL explicitly by assigning it to the `context` object
224 associated with each `REPLServer`.  For example:
225
226     // repl_test.js
227     var repl = require('repl'),
228         msg = 'message';
229
230     repl.start('> ').context.m = msg;
231
232 Things in the `context` object appear as local within the REPL:
233
234     mjr:~$ node repl_test.js
235     > m
236     'message'
237
238 There are a few special REPL commands:
239
240   - `.break` - While inputting a multi-line expression, sometimes you get lost
241     or just don't care about completing it. `.break` will start over.
242   - `.clear` - Resets the `context` object to an empty object and clears any
243     multi-line expression.
244   - `.exit` - Close the I/O stream, which will cause the REPL to exit.
245   - `.help` - Show this list of special commands.
246   - `.save` - Save the current REPL session to a file
247     >.save ./file/to/save.js
248   - `.load` - Load a file into the current REPL session.
249     >.load ./file/to/load.js
250
251 The following key combinations in the REPL have these special effects:
252
253   - `<ctrl>C` - Similar to the `.break` keyword.  Terminates the current
254     command.  Press twice on a blank line to forcibly exit.
255   - `<ctrl>D` - Similar to the `.exit` keyword.
256   - `<tab>` - Show both global and local(scope) variables
257
258
259 ### Customizing Object displays in the REPL
260
261 The REPL module internally uses
262 [util.inspect()][], when printing values. However, `util.inspect` delegates the
263  call to the object's `inspect()` function, if it has one. You can read more
264  about this delegation [here][].
265
266 For example, if you have defined an `inspect()` function on an object, like this:
267
268     > var obj = { foo: 'this will not show up in the inspect() output' };
269     undefined
270     > obj.inspect = function() {
271     ...   return { bar: 'baz' };
272     ... };
273     [Function]
274
275 and try to print `obj` in REPL, it will invoke the custom `inspect()` function:
276
277     > obj
278     { bar: 'baz' }
279
280 [Readline Interface]: readline.html#readline_class_interface
281 [util.inspect()]: util.html#util_util_inspect_object_options
282 [here]: util.html#util_custom_inspect_function_on_objects