d3600fd49dde42c1ce371758a06ff00b982a963f
[platform/upstream/nodejs.git] / doc / api / readline.markdown
1 # Readline
2
3     Stability: 2 - Stable
4
5 To use this module, do `require('readline')`. Readline allows reading of a
6 stream (such as `process.stdin`) on a line-by-line basis.
7
8 Note that once you've invoked this module, your io.js program will not
9 terminate until you've closed the interface. Here's how to allow your
10 program to gracefully exit:
11
12     var readline = require('readline');
13
14     var rl = readline.createInterface({
15       input: process.stdin,
16       output: process.stdout
17     });
18
19     rl.question("What do you think of io.js? ", function(answer) {
20       // TODO: Log the answer in a database
21       console.log("Thank you for your valuable feedback:", answer);
22
23       rl.close();
24     });
25
26 ## readline.createInterface(options)
27
28 Creates a readline `Interface` instance. Accepts an "options" Object that takes
29 the following values:
30
31  - `input` - the readable stream to listen to (Required).
32
33  - `output` - the writable stream to write readline data to (Optional).
34
35  - `completer` - an optional function that is used for Tab autocompletion. See
36    below for an example of using this.
37
38  - `terminal` - pass `true` if the `input` and `output` streams should be
39    treated like a TTY, and have ANSI/VT100 escape codes written to it.
40    Defaults to checking `isTTY` on the `output` stream upon instantiation.
41
42 The `completer` function is given the current line entered by the user, and
43 is supposed to return an Array with 2 entries:
44
45  1. An Array with matching entries for the completion.
46
47  2. The substring that was used for the matching.
48
49 Which ends up looking something like:
50 `[[substr1, substr2, ...], originalsubstring]`.
51
52 Example:
53
54     function completer(line) {
55       var completions = '.help .error .exit .quit .q'.split(' ')
56       var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
57       // show all completions if none found
58       return [hits.length ? hits : completions, line]
59     }
60
61 Also `completer` can be run in async mode if it accepts two arguments:
62
63     function completer(linePartial, callback) {
64       callback(null, [['123'], linePartial]);
65     }
66
67 `createInterface` is commonly used with `process.stdin` and
68 `process.stdout` in order to accept user input:
69
70     var readline = require('readline');
71     var rl = readline.createInterface({
72       input: process.stdin,
73       output: process.stdout
74     });
75
76 Once you have a readline instance, you most commonly listen for the
77 `"line"` event.
78
79 If `terminal` is `true` for this instance then the `output` stream will get
80 the best compatibility if it defines an `output.columns` property, and fires
81 a `"resize"` event on the `output` if/when the columns ever change
82 (`process.stdout` does this automatically when it is a TTY).
83
84 ## Class: Interface
85
86 The class that represents a readline interface with an input and output
87 stream.
88
89 ### rl.setPrompt(prompt)
90
91 Sets the prompt, for example when you run `iojs` on the command line, you see
92 `> `, which is io.js's prompt.
93
94 ### rl.prompt([preserveCursor])
95
96 Readies readline for input from the user, putting the current `setPrompt`
97 options on a new line, giving the user a new spot to write. Set `preserveCursor`
98 to `true` to prevent the cursor placement being reset to `0`.
99
100 This will also resume the `input` stream used with `createInterface` if it has
101 been paused.
102
103 If `output` is set to `null` or `undefined` when calling `createInterface`, the
104 prompt is not written.
105
106 ### rl.question(query, callback)
107
108 Prepends the prompt with `query` and invokes `callback` with the user's
109 response. Displays the query to the user, and then invokes `callback`
110 with the user's response after it has been typed.
111
112 This will also resume the `input` stream used with `createInterface` if
113 it has been paused.
114
115 If `output` is set to `null` or `undefined` when calling `createInterface`,
116 nothing is displayed.
117
118 Example usage:
119
120     interface.question('What is your favorite food?', function(answer) {
121       console.log('Oh, so your favorite food is ' + answer);
122     });
123
124 ### rl.pause()
125
126 Pauses the readline `input` stream, allowing it to be resumed later if needed.
127
128 Note that this doesn't immediately pause the stream of events. Several events may be emitted after calling `pause`, including `line`.
129
130 ### rl.resume()
131
132 Resumes the readline `input` stream.
133
134 ### rl.close()
135
136 Closes the `Interface` instance, relinquishing control on the `input` and
137 `output` streams. The "close" event will also be emitted.
138
139 ### rl.write(data[, key])
140
141 Writes `data` to `output` stream, unless `output` is set to `null` or
142 `undefined` when calling `createInterface`. `key` is an object literal to
143 represent a key sequence; available if the terminal is a TTY.
144
145 This will also resume the `input` stream if it has been paused.
146
147 Example:
148
149     rl.write('Delete me!');
150     // Simulate ctrl+u to delete the line written previously
151     rl.write(null, {ctrl: true, name: 'u'});
152
153 ## Events
154
155 ### Event: 'line'
156
157 `function (line) {}`
158
159 Emitted whenever the `input` stream receives a `\n`, usually received when the
160 user hits enter, or return. This is a good hook to listen for user input.
161
162 Example of listening for `line`:
163
164     rl.on('line', function (cmd) {
165       console.log('You just typed: '+cmd);
166     });
167
168 ### Event: 'pause'
169
170 `function () {}`
171
172 Emitted whenever the `input` stream is paused.
173
174 Also emitted whenever the `input` stream is not paused and receives the
175 `SIGCONT` event. (See events `SIGTSTP` and `SIGCONT`)
176
177 Example of listening for `pause`:
178
179     rl.on('pause', function() {
180       console.log('Readline paused.');
181     });
182
183 ### Event: 'resume'
184
185 `function () {}`
186
187 Emitted whenever the `input` stream is resumed.
188
189 Example of listening for `resume`:
190
191     rl.on('resume', function() {
192       console.log('Readline resumed.');
193     });
194
195 ### Event: 'close'
196
197 `function () {}`
198
199 Emitted when `close()` is called.
200
201 Also emitted when the `input` stream receives its "end" event. The `Interface`
202 instance should be considered "finished" once this is emitted. For example, when
203 the `input` stream receives `^D`, respectively known as `EOT`.
204
205 This event is also called if there is no `SIGINT` event listener present when
206 the `input` stream receives a `^C`, respectively known as `SIGINT`.
207
208 ### Event: 'SIGINT'
209
210 `function () {}`
211
212 Emitted whenever the `input` stream receives a `^C`, respectively known as
213 `SIGINT`. If there is no `SIGINT` event listener present when the `input`
214 stream receives a `SIGINT`, `pause` will be triggered.
215
216 Example of listening for `SIGINT`:
217
218     rl.on('SIGINT', function() {
219       rl.question('Are you sure you want to exit?', function(answer) {
220         if (answer.match(/^y(es)?$/i)) rl.pause();
221       });
222     });
223
224 ### Event: 'SIGTSTP'
225
226 `function () {}`
227
228 **This does not work on Windows.**
229
230 Emitted whenever the `input` stream receives a `^Z`, respectively known as
231 `SIGTSTP`. If there is no `SIGTSTP` event listener present when the `input`
232 stream receives a `SIGTSTP`, the program will be sent to the background.
233
234 When the program is resumed with `fg`, the `pause` and `SIGCONT` events will be
235 emitted. You can use either to resume the stream.
236
237 The `pause` and `SIGCONT` events will not be triggered if the stream was paused
238 before the program was sent to the background.
239
240 Example of listening for `SIGTSTP`:
241
242     rl.on('SIGTSTP', function() {
243       // This will override SIGTSTP and prevent the program from going to the
244       // background.
245       console.log('Caught SIGTSTP.');
246     });
247
248 ### Event: 'SIGCONT'
249
250 `function () {}`
251
252 **This does not work on Windows.**
253
254 Emitted whenever the `input` stream is sent to the background with `^Z`,
255 respectively known as `SIGTSTP`, and then continued with `fg(1)`. This event
256 only emits if the stream was not paused before sending the program to the
257 background.
258
259 Example of listening for `SIGCONT`:
260
261     rl.on('SIGCONT', function() {
262       // `prompt` will automatically resume the stream
263       rl.prompt();
264     });
265
266
267 ## Example: Tiny CLI
268
269 Here's an example of how to use all these together to craft a tiny command
270 line interface:
271
272     var readline = require('readline'),
273         rl = readline.createInterface(process.stdin, process.stdout);
274
275     rl.setPrompt('OHAI> ');
276     rl.prompt();
277
278     rl.on('line', function(line) {
279       switch(line.trim()) {
280         case 'hello':
281           console.log('world!');
282           break;
283         default:
284           console.log('Say what? I might have heard `' + line.trim() + '`');
285           break;
286       }
287       rl.prompt();
288     }).on('close', function() {
289       console.log('Have a great day!');
290       process.exit(0);
291     });
292
293 ## readline.cursorTo(stream, x, y)
294
295 Move cursor to the specified position in a given TTY stream.
296
297 ## readline.moveCursor(stream, dx, dy)
298
299 Move cursor relative to it's current position in a given TTY stream.
300
301 ## readline.clearLine(stream, dir)
302
303 Clears current line of given TTY stream in a specified direction.
304 `dir` should have one of following values:
305
306 * `-1` - to the left from cursor
307 * `1` - to the right from cursor
308 * `0` - the entire line
309
310 ## readline.clearScreenDown(stream)
311
312 Clears the screen from the current position of the cursor down.