Merge branch 'v1.x'
[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 The built-in repl (invoked by running `iojs` or `iojs -i`) may be controlled
33 via the following environment variables:
34
35  - `NODE_REPL_HISTORY_FILE` - if given, must be a path to a user-writable,
36    user-readable file. When a valid path is given, persistent history support
37    is enabled: REPL history will persist across `iojs` repl sessions.
38  - `NODE_REPL_HISTORY_SIZE` - defaults to `1000`. In conjunction with
39    `NODE_REPL_HISTORY_FILE`, controls how many lines of history will be
40    persisted. Must be a positive number.
41  - `NODE_REPL_MODE` - may be any of `sloppy`, `strict`, or `magic`. Defaults
42    to `magic`, which will automatically run "strict mode only" statements in
43    strict mode.
44
45 ## repl.start(options)
46
47 Returns and starts a `REPLServer` instance, that inherits from 
48 [Readline Interface][]. Accepts an "options" Object that takes 
49 the following values:
50
51  - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `.
52
53  - `input` - the readable stream to listen to. Defaults to `process.stdin`.
54
55  - `output` - the writable stream to write readline data to. Defaults to
56    `process.stdout`.
57
58  - `terminal` - pass `true` if the `stream` should be treated like a TTY, and
59    have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY`
60    on the `output` stream upon instantiation.
61
62  - `eval` - function that will be used to eval each given line. Defaults to
63    an async wrapper for `eval()`. See below for an example of a custom `eval`.
64
65  - `useColors` - a boolean which specifies whether or not the `writer` function
66    should output colors. If a different `writer` function is set then this does
67    nothing. Defaults to the repl's `terminal` value.
68
69  - `useGlobal` - if set to `true`, then the repl will use the `global` object,
70    instead of running scripts in a separate context. Defaults to `false`.
71
72  - `ignoreUndefined` - if set to `true`, then the repl will not output the
73    return value of command if it's `undefined`. Defaults to `false`.
74
75  - `writer` - the function to invoke for each command that gets evaluated which
76    returns the formatting (including coloring) to display. Defaults to
77    `util.inspect`.
78
79  - `replMode` - controls whether the repl runs all commands in strict mode,
80    default mode, or a hybrid mode ("magic" mode.) Acceptable values are:
81   * `repl.REPL_MODE_SLOPPY` - run commands in sloppy mode.
82   * `repl.REPL_MODE_STRICT` - run commands in strict mode. This is equivalent to
83   prefacing every repl statement with `'use strict'`.
84   * `repl.REPL_MODE_MAGIC` - attempt to run commands in default mode. If they
85   fail to parse, re-try in strict mode.
86
87 You can use your own `eval` function if it has following signature:
88
89     function eval(cmd, context, filename, callback) {
90       callback(null, result);
91     }
92
93 Multiple REPLs may be started against the same running instance of io.js.  Each
94 will share the same global object but will have unique I/O.
95
96 Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
97
98     var net = require("net"),
99         repl = require("repl");
100
101     connections = 0;
102
103     repl.start({
104       prompt: "io.js via stdin> ",
105       input: process.stdin,
106       output: process.stdout
107     });
108
109     net.createServer(function (socket) {
110       connections += 1;
111       repl.start({
112         prompt: "io.js via Unix socket> ",
113         input: socket,
114         output: socket
115       }).on('exit', function() {
116         socket.end();
117       })
118     }).listen("/tmp/iojs-repl-sock");
119
120     net.createServer(function (socket) {
121       connections += 1;
122       repl.start({
123         prompt: "io.js via TCP socket> ",
124         input: socket,
125         output: socket
126       }).on('exit', function() {
127         socket.end();
128       });
129     }).listen(5001);
130
131 Running this program from the command line will start a REPL on stdin.  Other
132 REPL clients may connect through the Unix socket or TCP socket. `telnet` is useful
133 for connecting to TCP sockets, and `socat` can be used to connect to both Unix and
134 TCP sockets.
135
136 By starting a REPL from a Unix socket-based server instead of stdin, you can
137 connect to a long-running io.js process without restarting it.
138
139 For an example of running a "full-featured" (`terminal`) REPL over
140 a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310
141
142 For an example of running a REPL instance over `curl(1)`,
143 see: https://gist.github.com/2053342
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     r.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     r = repl.start({ options ... });
173     someExtension.extend(r.context);
174
175     // When a new context is created extend it as well.
176     r.on('reset', function (context) {
177       console.log('repl has a new context');
178       someExtension.extend(context);
179     });
180
181
182 ## REPL Features
183
184 <!-- type=misc -->
185
186 Inside the REPL, Control+D will exit.  Multi-line expressions can be input.
187 Tab completion is supported for both global and local variables.
188
189 Core modules will be loaded on-demand into the environment. For example,
190 accessing `fs` will `require()` the `fs` module as `global.fs`.
191
192 The special variable `_` (underscore) contains the result of the last expression.
193
194     > [ "a", "b", "c" ]
195     [ 'a', 'b', 'c' ]
196     > _.length
197     3
198     > _ += 1
199     4
200
201 The REPL provides access to any variables in the global scope. You can expose
202 a variable to the REPL explicitly by assigning it to the `context` object
203 associated with each `REPLServer`.  For example:
204
205     // repl_test.js
206     var repl = require("repl"),
207         msg = "message";
208
209     repl.start("> ").context.m = msg;
210
211 Things in the `context` object appear as local within the REPL:
212
213     mjr:~$ iojs repl_test.js
214     > m
215     'message'
216
217 There are a few special REPL commands:
218
219   - `.break` - While inputting a multi-line expression, sometimes you get lost
220     or just don't care about completing it. `.break` will start over.
221   - `.clear` - Resets the `context` object to an empty object and clears any
222     multi-line expression.
223   - `.exit` - Close the I/O stream, which will cause the REPL to exit.
224   - `.help` - Show this list of special commands.
225   - `.save` - Save the current REPL session to a file
226     >.save ./file/to/save.js
227   - `.load` - Load a file into the current REPL session.
228     >.load ./file/to/load.js
229
230 The following key combinations in the REPL have these special effects:
231
232   - `<ctrl>C` - Similar to the `.break` keyword.  Terminates the current
233     command.  Press twice on a blank line to forcibly exit.
234   - `<ctrl>D` - Similar to the `.exit` keyword.
235