~yolanda.robla/ubuntu/trusty/nodejs/add_distribution

« back to all changes in this revision

Viewing changes to doc/api/readline.markdown

  • Committer: Package Import Robot
  • Author(s): Jérémy Lal
  • Date: 2013-08-14 00:16:46 UTC
  • mfrom: (7.1.40 sid)
  • Revision ID: package-import@ubuntu.com-20130814001646-bzlysfh8sd6mukbo
Tags: 0.10.15~dfsg1-4
* Update 2005 patch, adding a handful of tests that can fail on
  slow platforms.
* Add 1004 patch to fix test failures when writing NaN to buffer
  on mipsel.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Readline
2
2
 
3
 
    Stability: 3 - Stable
 
3
    Stability: 2 - Unstable
4
4
 
5
5
To use this module, do `require('readline')`. Readline allows reading of a
6
 
stream (such as STDIN) on a line-by-line basis.
 
6
stream (such as `process.stdin`) on a line-by-line basis.
7
7
 
8
8
Note that once you've invoked this module, your node program will not
9
 
terminate until you've closed the interface, and the STDIN stream. Here's how
10
 
to allow your program to gracefully terminate:
11
 
 
12
 
    var rl = require('readline');
13
 
 
14
 
    var i = rl.createInterface(process.stdin, process.stdout, null);
15
 
    i.question("What do you think of node.js?", function(answer) {
 
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 node.js? ", function(answer) {
16
20
      // TODO: Log the answer in a database
17
 
      console.log("Thank you for your valuable feedback.");
 
21
      console.log("Thank you for your valuable feedback:", answer);
18
22
 
19
 
      // These two lines together allow the program to terminate. Without
20
 
      // them, it would run forever.
21
 
      i.close();
22
 
      process.stdin.destroy();
 
23
      rl.close();
23
24
    });
24
25
 
25
 
## rl.createInterface(input, output, completer)
26
 
 
27
 
Takes two streams and creates a readline interface. The `completer` function
28
 
is used for autocompletion. When given a substring, it returns `[[substr1,
29
 
substr2, ...], originalsubstring]`.
 
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 (Required).
 
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 a 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
    }
30
60
 
31
61
Also `completer` can be run in async mode if it accepts two arguments:
32
62
 
33
 
  function completer(linePartial, callback) {
34
 
    callback(null, [['123'], linePartial]);
35
 
  }
 
63
    function completer(linePartial, callback) {
 
64
      callback(null, [['123'], linePartial]);
 
65
    }
36
66
 
37
67
`createInterface` is commonly used with `process.stdin` and
38
68
`process.stdout` in order to accept user input:
39
69
 
40
 
    var readline = require('readline'),
41
 
      rl = readline.createInterface(process.stdin, process.stdout);
 
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).
42
83
 
43
84
## Class: Interface
44
85
 
45
 
The class that represents a readline interface with a stdin and stdout
 
86
The class that represents a readline interface with an input and output
46
87
stream.
47
88
 
48
89
### rl.setPrompt(prompt, length)
50
91
Sets the prompt, for example when you run `node` on the command line, you see
51
92
`> `, which is node's prompt.
52
93
 
53
 
### rl.prompt()
 
94
### rl.prompt([preserveCursor])
54
95
 
55
96
Readies readline for input from the user, putting the current `setPrompt`
56
 
options on a new line, giving the user a new spot to write.
 
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.
57
102
 
58
103
### rl.question(query, callback)
59
104
 
60
105
Prepends the prompt with `query` and invokes `callback` with the user's
61
 
response. Displays the query to the user, and then invokes `callback` with the
62
 
user's response after it has been typed.
 
106
response. Displays the query to the user, and then invokes `callback`
 
107
with the user's response after it has been typed.
 
108
 
 
109
This will also resume the `input` stream used with `createInterface` if
 
110
it has been paused.
63
111
 
64
112
Example usage:
65
113
 
67
115
      console.log('Oh, so your favorite food is ' + answer);
68
116
    });
69
117
 
70
 
### rl.close()
71
 
 
72
 
  Closes tty.
73
 
 
74
118
### rl.pause()
75
119
 
76
 
  Pauses tty.
 
120
Pauses the readline `input` stream, allowing it to be resumed later if needed.
77
121
 
78
122
### rl.resume()
79
123
 
80
 
  Resumes tty.
81
 
 
82
 
### rl.write()
83
 
 
84
 
  Writes to tty.
 
124
Resumes the readline `input` stream.
 
125
 
 
126
### rl.close()
 
127
 
 
128
Closes the `Interface` instance, relinquishing control on the `input` and
 
129
`output` streams. The "close" event will also be emitted.
 
130
 
 
131
### rl.write(data, [key])
 
132
 
 
133
Writes `data` to `output` stream. `key` is an object literal to represent a key
 
134
sequence; available if the terminal is a TTY.
 
135
 
 
136
This will also resume the `input` stream if it has been paused.
 
137
 
 
138
Example:
 
139
 
 
140
    rl.write('Delete me!');
 
141
    // Simulate ctrl+u to delete the line written previously
 
142
    rl.write(null, {ctrl: true, name: 'u'});
 
143
 
 
144
## Events
85
145
 
86
146
### Event: 'line'
87
147
 
88
148
`function (line) {}`
89
149
 
90
 
Emitted whenever the `in` stream receives a `\n`, usually received when the
 
150
Emitted whenever the `input` stream receives a `\n`, usually received when the
91
151
user hits enter, or return. This is a good hook to listen for user input.
92
152
 
93
153
Example of listening for `line`:
96
156
      console.log('You just typed: '+cmd);
97
157
    });
98
158
 
 
159
### Event: 'pause'
 
160
 
 
161
`function () {}`
 
162
 
 
163
Emitted whenever the `input` stream is paused.
 
164
 
 
165
Also emitted whenever the `input` stream is not paused and receives the
 
166
`SIGCONT` event. (See events `SIGTSTP` and `SIGCONT`)
 
167
 
 
168
Example of listening for `pause`:
 
169
 
 
170
    rl.on('pause', function() {
 
171
      console.log('Readline paused.');
 
172
    });
 
173
 
 
174
### Event: 'resume'
 
175
 
 
176
`function () {}`
 
177
 
 
178
Emitted whenever the `input` stream is resumed.
 
179
 
 
180
Example of listening for `resume`:
 
181
 
 
182
    rl.on('resume', function() {
 
183
      console.log('Readline resumed.');
 
184
    });
 
185
 
99
186
### Event: 'close'
100
187
 
101
188
`function () {}`
102
189
 
103
 
Emitted whenever the `in` stream receives a `^C` or `^D`, respectively known
104
 
as `SIGINT` and `EOT`. This is a good way to know the user is finished using
105
 
your program.
106
 
 
107
 
Example of listening for `close`, and exiting the program afterward:
108
 
 
109
 
    rl.on('close', function() {
110
 
      console.log('goodbye!');
111
 
      process.exit(0);
112
 
    });
 
190
Emitted when `close()` is called.
 
191
 
 
192
Also emitted when the `input` stream receives its "end" event. The `Interface`
 
193
instance should be considered "finished" once this is emitted. For example, when
 
194
the `input` stream receives `^D`, respectively known as `EOT`.
 
195
 
 
196
This event is also called if there is no `SIGINT` event listener present when
 
197
the `input` stream receives a `^C`, respectively known as `SIGINT`.
 
198
 
 
199
### Event: 'SIGINT'
 
200
 
 
201
`function () {}`
 
202
 
 
203
Emitted whenever the `input` stream receives a `^C`, respectively known as
 
204
`SIGINT`. If there is no `SIGINT` event listener present when the `input`
 
205
stream receives a `SIGINT`, `pause` will be triggered.
 
206
 
 
207
Example of listening for `SIGINT`:
 
208
 
 
209
    rl.on('SIGINT', function() {
 
210
      rl.question('Are you sure you want to exit?', function(answer) {
 
211
        if (answer.match(/^y(es)?$/i)) rl.pause();
 
212
      });
 
213
    });
 
214
 
 
215
### Event: 'SIGTSTP'
 
216
 
 
217
`function () {}`
 
218
 
 
219
**This does not work on Windows.**
 
220
 
 
221
Emitted whenever the `input` stream receives a `^Z`, respectively known as
 
222
`SIGTSTP`. If there is no `SIGTSTP` event listener present when the `input`
 
223
stream receives a `SIGTSTP`, the program will be sent to the background.
 
224
 
 
225
When the program is resumed with `fg`, the `pause` and `SIGCONT` events will be
 
226
emitted. You can use either to resume the stream.
 
227
 
 
228
The `pause` and `SIGCONT` events will not be triggered if the stream was paused
 
229
before the program was sent to the background.
 
230
 
 
231
Example of listening for `SIGTSTP`:
 
232
 
 
233
    rl.on('SIGTSTP', function() {
 
234
      // This will override SIGTSTP and prevent the program from going to the
 
235
      // background.
 
236
      console.log('Caught SIGTSTP.');
 
237
    });
 
238
 
 
239
### Event: 'SIGCONT'
 
240
 
 
241
`function () {}`
 
242
 
 
243
**This does not work on Windows.**
 
244
 
 
245
Emitted whenever the `input` stream is sent to the background with `^Z`,
 
246
respectively known as `SIGTSTP`, and then continued with `fg(1)`. This event
 
247
only emits if the stream was not paused before sending the program to the
 
248
background.
 
249
 
 
250
Example of listening for `SIGCONT`:
 
251
 
 
252
    rl.on('SIGCONT', function() {
 
253
      // `prompt` will automatically resume the stream
 
254
      rl.prompt();
 
255
    });
 
256
 
 
257
 
 
258
## Example: Tiny CLI
113
259
 
114
260
Here's an example of how to use all these together to craft a tiny command
115
261
line interface:
116
262
 
117
263
    var readline = require('readline'),
118
 
      rl = readline.createInterface(process.stdin, process.stdout),
119
 
      prefix = 'OHAI> ';
 
264
        rl = readline.createInterface(process.stdin, process.stdout);
 
265
 
 
266
    rl.setPrompt('OHAI> ');
 
267
    rl.prompt();
120
268
 
121
269
    rl.on('line', function(line) {
122
270
      switch(line.trim()) {
127
275
          console.log('Say what? I might have heard `' + line.trim() + '`');
128
276
          break;
129
277
      }
130
 
      rl.setPrompt(prefix, prefix.length);
131
278
      rl.prompt();
132
279
    }).on('close', function() {
133
280
      console.log('Have a great day!');
134
281
      process.exit(0);
135
282
    });
136
 
    console.log(prefix + 'Good to see you. Try typing stuff.');
137
 
    rl.setPrompt(prefix, prefix.length);
138
 
    rl.prompt();
139
 
 
140
 
 
141
 
Take a look at this slightly more complicated
142
 
[example](https://gist.github.com/901104), and
143
 
[http-console](https://github.com/cloudhead/http-console) for a real-life use
144
 
case.
 
283