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