Merge branch 'v0.10'
[platform/upstream/nodejs.git] / doc / api / repl.markdown
1 # REPL
2
3     Stability: 3 - 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 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
33 ## repl.start(options)
34
35 Returns and starts a `REPLServer` instance, that inherits from 
36 [Readline Interface][]. Accepts an "options" Object that takes 
37 the following values:
38
39  - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `.
40
41  - `input` - the readable stream to listen to. Defaults to `process.stdin`.
42
43  - `output` - the writable stream to write readline data to. Defaults to
44    `process.stdout`.
45
46  - `terminal` - pass `true` if the `stream` should be treated like a TTY, and
47    have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY`
48    on the `output` stream upon instantiation.
49
50  - `eval` - function that will be used to eval each given line. Defaults to
51    an async wrapper for `eval()`. See below for an example of a custom `eval`.
52
53  - `useColors` - a boolean which specifies whether or not the `writer` function
54    should output colors. If a different `writer` function is set then this does
55    nothing. Defaults to the repl's `terminal` value.
56
57  - `useGlobal` - if set to `true`, then the repl will use the `global` object,
58    instead of running scripts in a separate context. Defaults to `false`.
59
60  - `ignoreUndefined` - if set to `true`, then the repl will not output the
61    return value of command if it's `undefined`. Defaults to `false`.
62
63  - `writer` - the function to invoke for each command that gets evaluated which
64    returns the formatting (including coloring) to display. Defaults to
65    `util.inspect`.
66
67 You can use your own `eval` function if it has following signature:
68
69     function eval(cmd, context, filename, callback) {
70       callback(null, result);
71     }
72
73 Multiple REPLs may be started against the same running instance of node.  Each
74 will share the same global object but will have unique I/O.
75
76 Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
77
78     var net = require("net"),
79         repl = require("repl");
80
81     connections = 0;
82
83     repl.start({
84       prompt: "node via stdin> ",
85       input: process.stdin,
86       output: process.stdout
87     });
88
89     net.createServer(function (socket) {
90       connections += 1;
91       repl.start({
92         prompt: "node via Unix socket> ",
93         input: socket,
94         output: socket
95       }).on('exit', function() {
96         socket.end();
97       })
98     }).listen("/tmp/node-repl-sock");
99
100     net.createServer(function (socket) {
101       connections += 1;
102       repl.start({
103         prompt: "node via TCP socket> ",
104         input: socket,
105         output: socket
106       }).on('exit', function() {
107         socket.end();
108       });
109     }).listen(5001);
110
111 Running this program from the command line will start a REPL on stdin.  Other
112 REPL clients may connect through the Unix socket or TCP socket. `telnet` is useful
113 for connecting to TCP sockets, and `socat` can be used to connect to both Unix and
114 TCP sockets.
115
116 By starting a REPL from a Unix socket-based server instead of stdin, you can
117 connect to a long-running node process without restarting it.
118
119 For an example of running a "full-featured" (`terminal`) REPL over
120 a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310
121
122 For an example of running a REPL instance over `curl(1)`,
123 see: https://gist.github.com/2053342
124
125 ### Event: 'exit'
126
127 `function () {}`
128
129 Emitted when the user exits the REPL in any of the defined ways. Namely, typing
130 `.exit` at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D
131 to signal "end" on the `input` stream.
132
133 Example of listening for `exit`:
134
135     r.on('exit', function () {
136       console.log('Got "exit" event from repl!');
137       process.exit();
138     });
139
140
141 ### Event: 'reset'
142
143 `function (context) {}`
144
145 Emitted when the REPL's context is reset. This happens when you type `.clear`.
146 If you start the repl with `{ useGlobal: true }` then this event will never
147 be emitted.
148
149 Example of listening for `reset`:
150
151     // Extend the initial repl context.
152     r = repl.start({ options ... });
153     someExtension.extend(r.context);
154
155     // When a new context is created extend it as well.
156     r.on('reset', function (context) {
157       console.log('repl has a new context');
158       someExtension.extend(context);
159     });
160
161
162 ## REPL Features
163
164 <!-- type=misc -->
165
166 Inside the REPL, Control+D will exit.  Multi-line expressions can be input.
167 Tab completion is supported for both global and local variables.
168
169 The special variable `_` (underscore) contains the result of the last expression.
170
171     > [ "a", "b", "c" ]
172     [ 'a', 'b', 'c' ]
173     > _.length
174     3
175     > _ += 1
176     4
177
178 The REPL provides access to any variables in the global scope. You can expose
179 a variable to the REPL explicitly by assigning it to the `context` object
180 associated with each `REPLServer`.  For example:
181
182     // repl_test.js
183     var repl = require("repl"),
184         msg = "message";
185
186     repl.start("> ").context.m = msg;
187
188 Things in the `context` object appear as local within the REPL:
189
190     mjr:~$ node repl_test.js
191     > m
192     'message'
193
194 There are a few special REPL commands:
195
196   - `.break` - While inputting a multi-line expression, sometimes you get lost
197     or just don't care about completing it. `.break` will start over.
198   - `.clear` - Resets the `context` object to an empty object and clears any
199     multi-line expression.
200   - `.exit` - Close the I/O stream, which will cause the REPL to exit.
201   - `.help` - Show this list of special commands.
202   - `.save` - Save the current REPL session to a file
203     >.save ./file/to/save.js
204   - `.load` - Load a file into the current REPL session.
205     >.load ./file/to/load.js
206
207 The following key combinations in the REPL have these special effects:
208
209   - `<ctrl>C` - Similar to the `.break` keyword.  Terminates the current
210     command.  Press twice on a blank line to forcibly exit.
211   - `<ctrl>D` - Similar to the `.exit` keyword.
212