UNPKG

69.8 kBMarkdownView Raw
1# readlineSync
2
3Synchronous [Readline](http://nodejs.org/api/readline.html) for interactively running to have a conversation with the user via a console(TTY).
4
5readlineSync tries to let your script have a conversation with the user via a console, even when the input/output stream is redirected like `your-script <foo.dat >bar.log`.
6
7<table>
8<tr><td><a href="#basic_options">Basic Options</a></td><td><a href="#utility_methods">Utility Methods</a></td><td><a href="#placeholders">Placeholders</a></td></tr>
9</table>
10
11* Simple case:
12
13```js
14var readlineSync = require('readline-sync');
15
16// Wait for user's response.
17var userName = readlineSync.question('May I have your name? :');
18console.log('Hi ' + userName + '!');
19
20// Handle the secret text (e.g. password).
21var favFood = readlineSync.question('What is your favorite food? :', {
22 hideEchoBack: true // The typed text on screen is hidden by `*` (default).
23});
24console.log('Oh, ' + userName + ' loves ' + favFood + '!');
25```
26
27```console
28May I have your name? :CookieMonster
29Hi CookieMonster!
30What is your favorite food? :****
31Oh, CookieMonster loves tofu!
32```
33
34* Get the user's response by a single key without the Enter key:
35
36```js
37var readlineSync = require('readline-sync');
38if (readlineSync.keyInYN('Do you want this module?')) {
39 // 'Y' key was pressed.
40 console.log('Installing now...');
41 // Do something...
42} else {
43 // Another key was pressed.
44 console.log('Searching another...');
45 // Do something...
46}
47```
48
49* Let the user choose an item from a list:
50
51```js
52var readlineSync = require('readline-sync'),
53 animals = ['Lion', 'Elephant', 'Crocodile', 'Giraffe', 'Hippo'],
54 index = readlineSync.keyInSelect(animals, 'Which animal?');
55console.log('Ok, ' + animals[index] + ' goes to your room.');
56```
57
58```console
59[1] Lion
60[2] Elephant
61[3] Crocodile
62[4] Giraffe
63[5] Hippo
64[0] CANCEL
65
66Which animal? [1...5 / 0] :2
67Ok, Elephant goes to your room.
68```
69
70* An UI like the Range Slider:
71(Press `Z` or `X` key to change a value, and Space Bar to exit)
72
73```js
74var readlineSync = require('readline-sync'),
75 MAX = 60, MIN = 0, value = 30, key;
76console.log('\n\n' + (new Array(20)).join(' ') +
77 '[Z] <- -> [X] FIX: [SPACE]\n');
78while (true) {
79 console.log('\x1B[1A\x1B[K|' +
80 (new Array(value + 1)).join('-') + 'O' +
81 (new Array(MAX - value + 1)).join('-') + '| ' + value);
82 key = readlineSync.keyIn('',
83 {hideEchoBack: true, mask: '', limit: 'zx '});
84 if (key === 'z') { if (value > MIN) { value--; } }
85 else if (key === 'x') { if (value < MAX) { value++; } }
86 else { break; }
87}
88console.log('\nA value the user requested: ' + value);
89```
90
91![sample](screen_03.gif)
92
93* Handle the commands repeatedly, such as the shell interface:
94
95```js
96readlineSync.promptCLLoop({
97 add: function(target, into) {
98 console.log(target + ' is added into ' + into + '.');
99 // Do something...
100 },
101 remove: function(target) {
102 console.log(target + ' is removed.');
103 // Do something...
104 },
105 bye: function() { return true; }
106});
107console.log('Exited');
108```
109
110```console
111> add pic01.png archive
112pic01.png is added into archive.
113> delete pic01.png
114Requested command is not available.
115> remove pic01.png
116pic01.png is removed.
117> bye
118Exited
119```
120
121## <a name="installation"></a>Installation
122
123```shell
124npm install readline-sync
125```
126
127## <a name="quick_start"></a>Quick Start
128
129**How does the user input?**
130
131- [Type a reply to a question, and press the Enter key](#quick_start-a) (A)
132- [Type a keyword like a command in prompt, and press the Enter key](#quick_start-b) (B)
133- [Press a single key without the Enter key](#quick_start-c) (C)
134
135<a name="quick_start-a"></a>**(A) What does the user input?**
136
137- [E-mail address](#utility_methods-questionemail)
138- [New password](#utility_methods-questionnewpassword)
139- [Integer number](#utility_methods-questionint)
140- [Floating-point number](#utility_methods-questionfloat)
141- [Local file/directory path](#utility_methods-questionpath)
142- [Others](#basic_methods-question)
143
144<a name="quick_start-b"></a>**(B) What does your script do?**
145
146- [Receive a parsed command-name and arguments](#utility_methods-promptcl)
147- [Receive an input repeatedly](#utility_methods-promptloop)
148- [Receive a parsed command-name and arguments repeatedly](#utility_methods-promptclloop)
149- [Receive an input with prompt that is similar to that of the user's shell](#utility_methods-promptsimshell)
150- [Others](#basic_methods-prompt)
151
152<a name="quick_start-c"></a>**(C) What does the user do?**
153
154- [Say "Yes" or "No"](#utility_methods-keyinyn)
155- [Say "Yes" or "No" explicitly](#utility_methods-keyinynstrict)
156- [Make the running of script continue when ready](#utility_methods-keyinpause)
157- [Choose an item from a list](#utility_methods-keyinselect)
158- [Others](#basic_methods-keyin)
159
160## <a name="basic_methods"></a>Basic Methods
161
162These are used to control details of the behavior. It is recommended to use the [Utility Methods](#utility_methods) instead of Basic Methods if it satisfy your request.
163
164### <a name="basic_methods-question"></a>`question`
165
166```js
167answer = readlineSync.question([query[, options]])
168```
169
170Display a `query` to the user if it's specified, and then return the input from the user after it has been typed and the Enter key was pressed.
171You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). **If you let the user input the secret text (e.g. password), you should consider [`hideEchoBack`](#basic_options-hideechoback) option.**
172
173The `query` may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also)
174It can include the [placeholders](#placeholders).
175
176For example:
177
178```js
179program = readlineSync.question('Which program starts do you want? :', {
180 defaultInput: 'firefox'
181});
182```
183
184### <a name="basic_methods-prompt"></a>`prompt`
185
186```js
187input = readlineSync.prompt([options])
188```
189
190Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then return the input from the user after it has been typed and the Enter key was pressed.
191You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.).
192
193For example:
194
195```js
196while (true) {
197 command = readlineSync.prompt();
198 // Do something...
199}
200```
201
202### <a name="basic_methods-keyin"></a>`keyIn`
203
204```js
205pressedKey = readlineSync.keyIn([query[, options]])
206```
207
208Display a `query` to the user if it's specified, and then return a character as a key immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input.
209You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. ignoring keys except some keys, checking target key, etc.).
210
211The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
212
213For example:
214
215```js
216menuId = readlineSync.keyIn('Hit 1...5 key :', {limit: '$<1-5>'});
217```
218
219### <a name="basic_methods-setdefaultoptions"></a>`setDefaultOptions`
220
221```js
222currentDefaultOptions = readlineSync.setDefaultOptions([newDefaultOptions])
223```
224
225Change the [Default Options](#basic_options) to the values of properties of `newDefaultOptions` Object.
226All it takes is to specify options that you want change, because unspecified options are not updated.
227
228## <a name="basic_options"></a>Basic Options
229
230[`prompt`](#basic_options-prompt), [`hideEchoBack`](#basic_options-hideechoback), [`mask`](#basic_options-mask), [`limit`](#basic_options-limit), [`limitMessage`](#basic_options-limitmessage), [`defaultInput`](#basic_options-defaultinput), [`trueValue`, `falseValue`](#basic_options-truevalue_falsevalue), [`caseSensitive`](#basic_options-casesensitive), [`keepWhitespace`](#basic_options-keepwhitespace), [`encoding`](#basic_options-encoding), [`bufferSize`](#basic_options-buffersize), [`print`](#basic_options-print), [`history`](#basic_options-history), [`cd`](#basic_options-cd)
231
232An `options` Object can be specified to the methods to control the behavior of readlineSync. The options that were not specified to the methods are got from the Default Options. You can change the Default Options by [`setDefaultOptions`](#basic_methods-setdefaultoptions) method anytime, and it is kept until a current process is exited.
233Specify the options that are often used to the Default Options, and specify temporary options to the methods.
234
235For example:
236
237```js
238readlineSync.setDefaultOptions({limit: ['green', 'yellow', 'red']});
239a1 = readlineSync.question('Which color of signal? :'); // Input is limited to 3 things.
240a2 = readlineSync.question('Which color of signal? :'); // It's limited yet.
241a3 = readlineSync.question('What is your favorite color? :', {limit: null}); // It's unlimited temporarily.
242a4 = readlineSync.question('Which color of signal? :'); // It's limited again.
243readlineSync.setDefaultOptions({limit: ['beef', 'chicken']});
244a5 = readlineSync.question('Beef or Chicken? :'); // Input is limited to new 2 things.
245a6 = readlineSync.question('And you? :'); // It's limited to 2 things yet.
246```
247
248The Object as `options` can have following properties.
249
250### <a name="basic_options-prompt"></a>`prompt`
251
252_For `prompt*` methods only_
253*Type:* string or others
254*Default:* `'> '`
255
256Set the prompt-sign that is displayed to the user by `prompt*` methods. For example you see `> ` that is Node.js's prompt-sign when you run `node` on the command line.
257This may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string every time (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also)
258It can include the [placeholders](#placeholders).
259
260For example:
261
262```js
263readlineSync.setDefaultOptions({prompt: '$ '});
264```
265
266```js
267// Display the memory usage always.
268readlineSync.setDefaultOptions({
269 prompt: { // Simple Object that has toString method.
270 toString: function() {
271 var rss = process.memoryUsage().rss;
272 return '[' + (rss > 1024 ? Math.round(rss / 1024) + 'k' : rss) + 'b]$ ';
273 }
274 }
275});
276```
277
278```console
279[13148kb]$ foo
280[13160kb]$ bar
281[13200kb]$
282```
283
284### <a name="basic_options-hideechoback"></a>`hideEchoBack`
285
286*Type:* boolean
287*Default:* `false`
288
289If `true` is specified, hide the secret text (e.g. password) which is typed by user on screen by the mask characters (see [`mask`](#basic_options-mask) option).
290
291For example:
292
293```js
294password = readlineSync.question('PASSWORD :', {hideEchoBack: true});
295console.log('Login ...');
296```
297
298```console
299PASSWORD :********
300Login ...
301```
302
303### <a name="basic_options-mask"></a>`mask`
304
305*Type:* string
306*Default:* `'*'`
307
308Set the mask characters that are shown instead of the secret text (e.g. password) when `true` is specified to [`hideEchoBack`](#basic_options-hideechoback) option. If you want to show nothing, specify `''`. (But it might be not user friendly in some cases.)
309*Note:* In some cases (e.g. when the input stream is redirected on Windows XP), `'*'` or `''` might be used whether other one is specified.
310
311For example:
312
313```js
314secret = readlineSync.question('Please whisper sweet words :', {
315 hideEchoBack: true,
316 mask: require('chalk').magenta('\u2665')
317});
318```
319
320![sample](screen_02.gif)
321
322### <a name="basic_options-limit"></a>`limit`
323
324Limit the user's input.
325The usage differ depending on the method.
326
327#### <a name="basic_options-limit-for_question_and_prompt_methods"></a>For `question*` and `prompt*` methods
328
329*Type:* string, number, RegExp, function or Array
330*Default:* `[]`
331
332Accept only the input that matches value that is specified to this. If the user input others, display a string that is specified to [`limitMessage`](#basic_options-limitmessage) option, and wait for reinput.
333
334* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option.
335* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`.
336* The RegExp tests the input.
337* The function that returns a boolean to indicate whether it matches is called with the input.
338
339One of above or an Array that includes multiple things (or Array includes Array) can be specified.
340
341For example:
342
343```js
344command = readlineSync.prompt({limit: ['add', 'remove', /^clear( all)?$/]});
345// ** But `promptCL` method should be used instead of this. **
346```
347
348```js
349file = readlineSync.question('Text File :', {limit: /\.txt$/i});
350// ** But `questionPath` method should be used instead of this. **
351```
352
353```js
354ip = readlineSync.question('IP Address :', {limit: function(input) {
355 return require('net').isIP(input); // Valid IP Address
356}});
357```
358
359```js
360availableActions = [];
361if (!blockExists()) { availableActions.push('jump'); }
362if (isLarge(place)) { availableActions.push('run'); }
363if (isNew(shoes)) { availableActions.push('kick'); }
364if (isNearby(enemy)) { availableActions.push('punch'); }
365action = readlineSync.prompt({limit: availableActions});
366// ** But `promptCL` method should be used instead of this. **
367```
368
369#### <a name="basic_options-limit-for_keyin_method"></a>For `keyIn*` method
370
371*Type:* string, number or Array
372*Default:* `[]`
373
374Accept only the key that matches value that is specified to this, ignore others.
375Specify the characters as the key. All strings or Array of those are decomposed into single characters. For example, `'abcde'` or `['a', 'bc', ['d', 'e']]` are the same as `['a', 'b', 'c', 'd', 'e']`.
376These strings are compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option.
377
378The [placeholders](#placeholders) like `'$<a-e>'` are replaced to an Array that is the character list like `['a', 'b', 'c', 'd', 'e']`.
379
380For example:
381
382```js
383direction = readlineSync.keyIn('Left or Right? :', {limit: 'lr'}); // 'l' or 'r'
384```
385
386```js
387dice = readlineSync.keyIn('Roll the dice, What will the result be? :',
388 {limit: '$<1-6>'}); // range of '1' to '6'
389```
390
391### <a name="basic_options-limitmessage"></a>`limitMessage`
392
393_For `question*` and `prompt*` methods only_
394*Type:* string
395*Default:* `'Input another, please.$<( [)limit(])>'`
396
397Display this to the user when the [`limit`](#basic_options-limit) option is specified and the user input others.
398The [placeholders](#placeholders) can be included.
399
400For example:
401
402```js
403file = readlineSync.question('Name of Text File :', {
404 limit: /\.txt$/i,
405 limitMessage: 'Sorry, $<lastInput> is not text file.'
406});
407```
408
409### <a name="basic_options-defaultinput"></a>`defaultInput`
410
411_For `question*` and `prompt*` methods only_
412*Type:* string
413*Default:* `''`
414
415If the user input empty text (i.e. pressed the Enter key only), return this.
416
417For example:
418
419```js
420lang = readlineSync.question('Which language? :', {defaultInput: 'javascript'});
421```
422
423### <a name="basic_options-truevalue_falsevalue"></a>`trueValue`, `falseValue`
424
425*Type:* string, number, RegExp, function or Array
426*Default:* `[]`
427
428If the input matches `trueValue`, return `true`. If the input matches `falseValue`, return `false`. In any other case, return the input.
429
430* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option.
431* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. Note that in `keyIn*` method, the input is every time one character (i.e. the number that is specified must be an integer within the range of `0` to `9`).
432* The RegExp tests the input.
433* The function that returns a boolean to indicate whether it matches is called with the input.
434
435One of above or an Array that includes multiple things (or Array includes Array) can be specified.
436
437For example:
438
439```js
440answer = readlineSync.question('How do you like it? :', {
441 trueValue: ['yes', 'yeah', 'yep'],
442 falseValue: ['no', 'nah', 'nope']
443});
444if (answer === true) {
445 console.log('Let\'s go!');
446} else if (answer === false) {
447 console.log('Oh... It\'s ok...');
448} else {
449 console.log('Sorry. What does "' + answer + '" you said mean?');
450}
451```
452
453### <a name="basic_options-casesensitive"></a>`caseSensitive`
454
455*Type:* boolean
456*Default:* `false`
457
458By default, the string comparisons are case-insensitive (i.e. `a` equals `A`). If `true` is specified, it is case-sensitive, the cases are not ignored (i.e. `a` is different from `A`).
459It affects: [`limit`](#basic_options-limit), [`trueValue`](#basic_options-truevalue_falsevalue), [`falseValue`](#basic_options-truevalue_falsevalue), some [placeholders](#placeholders), and some [Utility Methods](#utility_methods).
460
461### <a name="basic_options-keepwhitespace"></a>`keepWhitespace`
462
463_For `question*` and `prompt*` methods only_
464*Type:* boolean
465*Default:* `false`
466
467By default, remove the leading and trailing white spaces from the input text. If `true` is specified, don't remove those.
468
469### <a name="basic_options-encoding"></a>`encoding`
470
471*Type:* string
472*Default:* `'utf8'`
473
474Set the encoding method of the input and output.
475
476### <a name="basic_options-buffersize"></a>`bufferSize`
477
478_For `question*` and `prompt*` methods only_
479*Type:* number
480*Default:* `1024`
481
482When readlineSync reads from a console directly (without external program), use a size `bufferSize` buffer.
483Even if the input by user exceeds it, it's usually no problem, because the buffer is used repeatedly. But some platforms's (e.g. Windows) console might not accept input that exceeds it. And set an enough size.
484Note that this might be limited by [version of Node.js](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding) and environment running your script (Big buffer size is usually not required). (See also: [issue](https://github.com/nodejs/node/issues/4660), [PR](https://github.com/nodejs/node/pull/4682))
485
486### <a name="basic_options-print"></a>`print`
487
488*Type:* function or `undefined`
489*Default:* `undefined`
490
491Call the specified function with every output. The function is given two arguments, `display` as an output text, and a value of [`encoding`](#basic_options-encoding) option.
492
493For example:
494
495* Pass the plain texts to the Logger (e.g. [log4js](https://github.com/nomiddlename/log4js-node)), after clean the colored texts.
496
497![sample](screen_01.png)
498
499```js
500var readlineSync = require('readline-sync'),
501 chalk = require('chalk'),
502 log4js = require('log4js'),
503 logger, user, pw, command;
504
505log4js.configure({appenders: [{type: 'file', filename: 'fooApp.log'}]});
506logger = log4js.getLogger('fooApp');
507
508readlineSync.setDefaultOptions({
509 print: function(display, encoding)
510 { logger.info(chalk.stripColor(display)); }, // Remove ctrl-chars.
511 prompt: chalk.red.bold('> ')
512});
513
514console.log(chalk.black.bold.bgYellow(' Your Account '));
515user = readlineSync.question(chalk.gray.underline(' USER NAME ') + ' :');
516pw = readlineSync.question(chalk.gray.underline(' PASSWORD ') + ' :',
517 {hideEchoBack: true});
518// Authorization ...
519console.log(chalk.green('Welcome, ' + user + '!'));
520command = readlineSync.prompt();
521```
522
523* Output a conversation to a file when an output stream is redirected to record those into a file like `your-script >foo.log`. That is, a conversation isn't outputted to `foo.log` without this code.
524
525```js
526readlineSync.setDefaultOptions({
527 print: function(display, encoding)
528 { process.stdout.write(display, encoding); }
529});
530var name = readlineSync.question('May I have your name? :');
531var loc = readlineSync.question('Hi ' + name + '! Where do you live? :');
532```
533
534* Let somebody hear our conversation in real time.
535It just uses a fifo with above sample code that was named `conv.js`.
536
537Another terminal:
538
539```shell
540mkfifo /tmp/fifo
541cat /tmp/fifo
542```
543
544My terminal:
545
546```shell
547node conv.js >/tmp/fifo
548```
549
550```console
551May I have your name? :Oz
552Hi Oz! Where do you live? :Emerald City
553```
554
555And then, another terminal shows this synchronously:
556
557```console
558May I have your name? :Oz
559Hi Oz! Where do you live? :Emerald City
560```
561
562### <a name="basic_options-history"></a>`history`
563
564_For `question*` and `prompt*` methods only_
565*Type:* boolean
566*Default:* `true`
567
568readlineSync supports a history expansion feature that is similar to that of the shell. If `false` is specified, disable this feature.
569*It keeps a previous input only.* That is, only `!!`, `!-1`, `!!:p` and `!-1:p` like bash or zsh etc. are supported.
570
571* `!!` or `!-1`: Return a previous input.
572* `!!:p` or `!-1:p`: Display a previous input but do not return it, and wait for reinput.
573
574For example:
575
576```js
577while (true) {
578 input = readlineSync.prompt();
579 console.log('-- You said "' + input + '"');
580}
581```
582
583```console
584> hello
585-- You said "hello"
586> !!
587hello
588-- You said "hello"
589> !!:p
590hello
591> bye
592-- You said "bye"
593```
594
595### <a name="basic_options-cd"></a>`cd`
596
597_For `question*` and `prompt*` methods only_
598*Type:* boolean
599*Default:* `false`
600
601readlineSync supports the changing the current working directory feature that is similar to the `cd` and `pwd` commands in the shell. If `true` is specified, enable this feature.
602This helps the user when you let the user input the multiple local files or directories.
603It supports `cd` and `pwd` commands.
604
605* `cd <path>`: Change the current working directory to `<path>`. The `<path>` can include `~` as the home directory.
606* `pwd`: Display the current working directory.
607
608When these were input, do not return, and wait for reinput.
609
610For example:
611
612```js
613while (true) {
614 file = readlineSync.questionPath('File :');
615 console.log('-- Specified file is ' + file);
616}
617```
618
619```console
620File :cd foo-dir/bar-dir
621File :pwd
622/path/to/foo-dir/bar-dir
623File :file-a.js
624-- Specified file is /path/to/foo-dir/bar-dir/file-a.js
625File :file-b.png
626-- Specified file is /path/to/foo-dir/bar-dir/file-b.png
627File :file-c.html
628-- Specified file is /path/to/foo-dir/bar-dir/file-c.html
629```
630
631## <a name="utility_methods"></a>Utility Methods
632
633[`questionEMail`](#utility_methods-questionemail), [`questionNewPassword`](#utility_methods-questionnewpassword), [`questionInt`](#utility_methods-questionint), [`questionFloat`](#utility_methods-questionfloat), [`questionPath`](#utility_methods-questionpath), [`promptCL`](#utility_methods-promptcl), [`promptLoop`](#utility_methods-promptloop), [`promptCLLoop`](#utility_methods-promptclloop), [`promptSimShell`](#utility_methods-promptsimshell), [`keyInYN`](#utility_methods-keyinyn), [`keyInYNStrict`](#utility_methods-keyinynstrict), [`keyInPause`](#utility_methods-keyinpause), [`keyInSelect`](#utility_methods-keyinselect)
634
635These are convenient methods that are extended [Basic Methods](#basic_methods) to be used easily.
636
637### <a name="utility_methods-questionemail"></a>`questionEMail`
638
639```js
640email = readlineSync.questionEMail([query[, options]])
641```
642
643Display a `query` to the user if it's specified, and then accept only a valid e-mail address, and then return it after the Enter key was pressed.
644
645The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
646The default value of `query` is `'Input e-mail address :'`.
647
648*Note:* The valid e-mail address requirement is a willful violation of [RFC5322](http://tools.ietf.org/html/rfc5322), this is defined in [HTML5](http://www.w3.org/TR/html5/forms.html). This works enough to prevent the user mistaking. If you want to change it, specify [`limit`](#basic_options-limit) option.
649
650For example:
651
652```js
653email = readlineSync.questionEMail();
654console.log('-- E-mail is ' + email);
655```
656
657```console
658Input e-mail address :abc
659Input valid e-mail address, please.
660Input e-mail address :mail@example.com
661-- E-mail is mail@example.com
662```
663
664#### <a name="utility_methods-questionemail-options"></a>Options
665
666The following options have independent default value that is not affected by [Default Options](#basic_options).
667
668| Option Name | Default Value |
669|-------------------|---------------|
670| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
671| [`limit`](#basic_options-limit) | RegExp by [HTML5](http://www.w3.org/TR/html5/forms.html) |
672| [`limitMessage`](#basic_options-limitmessage) | `'Input valid e-mail address, please.'` |
673| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` |
674| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` |
675
676The following options work as shown in the [Basic Options](#basic_options) section.
677
678<table>
679<tr><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-casesensitive"><code>caseSensitive</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td></tr>
680<tr><td><a href="#basic_options-print"><code>print</code></a></td><td><a href="#basic_options-history"><code>history</code></a></td></tr>
681</table>
682
683### <a name="utility_methods-questionnewpassword"></a>`questionNewPassword`
684
685```js
686password = readlineSync.questionNewPassword([query[, options]])
687```
688
689Display a `query` to the user if it's specified, and then accept only a valid password, and then request same one again, and then return it after the Enter key was pressed.
690It's the password, or something that is the secret text like the password.
691You can specify the valid password requirement to the options.
692
693The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
694The default value of `query` is `'Input new password :'`.
695
696*Note:* Only the form of password is checked. Check it more if you want. For example, [zxcvbn](https://github.com/dropbox/zxcvbn) is password strength estimation library.
697
698For example:
699
700```js
701password = readlineSync.questionNewPassword();
702console.log('-- Password is ' + password);
703```
704
705```console
706Input new password :************
707It can include: 0...9, A...Z, a...z, !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
708And the length must be: 12...24
709Input new password :*************
710Reinput a same one to confirm it :*************
711It differs from first one. Hit only the Enter key if you want to retry from first one.
712Reinput a same one to confirm it :*************
713-- Password is _my_password_
714```
715
716#### <a name="utility_methods-questionnewpassword-options"></a>Options
717
718The following options have independent default value that is not affected by [Default Options](#basic_options).
719
720| Option Name | Default Value |
721|-------------------|---------------|
722| [`hideEchoBack`](#basic_options-hideechoback) | `true` |
723| [`mask`](#basic_options-mask) | `'*'` |
724| [`limitMessage`](#basic_options-limitmessage) | `'It can include: $<charlist>\nAnd the length must be: $<length>'` |
725| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` |
726| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` |
727| [`caseSensitive`](#basic_options-casesensitive) | `true` |
728
729The following options work as shown in the [Basic Options](#basic_options) section.
730
731<table>
732<tr><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-keepwhitespace"><code>keepWhitespace</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td><td><a href="#basic_options-print"><code>print</code></a></td></tr>
733</table>
734
735And the following additional options are available.
736
737##### <a name="utility_methods-questionnewpassword-options-charlist"></a>`charlist`
738
739*Type:* string
740*Default:* `'$<!-~>'`
741
742A string as the characters that can be included in the password. For example, if `'abc123'` is specified, the passwords that include any character other than these 6 characters are refused.
743The [placeholders](#placeholders) like `'$<a-e>'` are replaced to the characters like `'abcde'`.
744
745For example, let the user input a password that is created with alphabet and some symbols:
746
747```js
748password = readlineSync.questionNewPassword('PASSWORD :', {charlist: '$<a-z>#$@%'});
749```
750
751##### <a name="utility_methods-questionnewpassword-options-min_max"></a>`min`, `max`
752
753*Type:* number
754*Default:* `min`: `12`, `max`: `24`
755
756`min`: A number as a minimum length of the password.
757`max`: A number as a maximum length of the password.
758
759##### <a name="utility_methods-questionnewpassword-options-confirmmessage"></a>`confirmMessage`
760
761*Type:* string or others
762*Default:* `'Reinput a same one to confirm it :'`
763
764A message that lets the user input the same password again.
765It can include the [placeholders](#placeholders).
766If this is not string, it is converted to string (i.e. `toString` method is called).
767
768##### <a name="utility_methods-questionnewpassword-options-unmatchmessage"></a>`unmatchMessage`
769
770*Type:* string or others
771*Default:* `'It differs from first one. Hit only the Enter key if you want to retry from first one.'`
772
773A warning message that is displayed when the second input did not match first one.
774This is converted the same as the [`confirmMessage`](#utility_methods-questionnewpassword-options-confirmmessage) option.
775
776#### <a name="utility_methods-questionnewpassword-additional_placeholders"></a>Additional Placeholders
777
778The following additional [placeholder](#placeholders) parameters are available.
779
780##### <a name="utility_methods-questionnewpassword-additional_placeholders-charlist"></a>`charlist`
781
782A current value of [`charlist`](#utility_methods-questionnewpassword-options-charlist) option that is converted to human readable if possible. (e.g. `'A...Z'`)
783
784##### <a name="utility_methods-questionnewpassword-additional_placeholders-length"></a>`length`
785
786A current value of [`min` and `max`](#utility_methods-questionnewpassword-options-min_max) option that is converted to human readable. (e.g. `'12...24'`)
787
788### <a name="utility_methods-questionint"></a>`questionInt`
789
790```js
791numInt = readlineSync.questionInt([query[, options]])
792```
793
794Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as an integer, and then return the number (not string) after the Enter key was pressed.
795This parses the input as much as possible by `parseInt()`. For example, it interprets `' 5 '`, `'5.6'`, `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`.
796
797The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
798
799#### <a name="utility_methods-questionint-options"></a>Options
800
801The following option has independent default value that is not affected by [Default Options](#basic_options).
802
803| Option Name | Default Value |
804|-------------------|---------------|
805| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` |
806
807The following options work as shown in the [Basic Options](#basic_options) section.
808
809<table>
810<tr><td><a href="#basic_options-hideechoback"><code>hideEchoBack</code></a></td><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td></tr>
811<tr><td><a href="#basic_options-print"><code>print</code></a></td><td><a href="#basic_options-history"><code>history</code></a></td></tr>
812</table>
813
814### <a name="utility_methods-questionfloat"></a>`questionFloat`
815
816```js
817numFloat = readlineSync.questionFloat([query[, options]])
818```
819
820Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as a floating-point number, and then return the number (not string) after the Enter key was pressed.
821This parses the input as much as possible by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`.
822
823The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
824
825#### <a name="utility_methods-questionfloat-options"></a>Options
826
827The following option has independent default value that is not affected by [Default Options](#basic_options).
828
829| Option Name | Default Value |
830|-------------------|---------------|
831| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` |
832
833The following options work as shown in the [Basic Options](#basic_options) section.
834
835<table>
836<tr><td><a href="#basic_options-hideechoback"><code>hideEchoBack</code></a></td><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td></tr>
837<tr><td><a href="#basic_options-print"><code>print</code></a></td><td><a href="#basic_options-history"><code>history</code></a></td></tr>
838</table>
839
840### <a name="utility_methods-questionpath"></a>`questionPath`
841
842```js
843path = readlineSync.questionPath([query[, options]])
844```
845
846Display a `query` to the user if it's specified, and then accept only a valid local file or directory path, and then return an absolute path after the Enter key was pressed.
847The `~` that is input by the user is replaced to the home directory.
848You can specify the valid local file or directory path requirement to the options. And you can make it create a new file or directory when it doesn't exist.
849
850It is recommended to use this method with the [`cd`](#basic_options-cd) option. (Default: `true`)
851
852The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
853The default value of `query` is `'Input path (you can "cd" and "pwd") :'`.
854
855For example:
856
857```js
858sourceFile = readlineSync.questionPath('Read from :', {
859 isFile: true
860});
861console.log('-- sourceFile: ' + sourceFile);
862
863saveDir = readlineSync.questionPath('Save to :', {
864 isDirectory: true,
865 exists: null,
866 create: true
867});
868console.log('-- saveDir: ' + saveDir);
869```
870
871```console
872Read from :~/fileA
873No such file or directory: /home/user/fileA
874Input valid path, please.
875Read from :pwd
876/path/to/work
877Read from :cd ~/project-1
878Read from :fileA
879-- sourceFile: /home/user/project-1/fileA
880Save to :~/deploy/data
881-- saveDir: /home/user/deploy/data
882```
883
884#### <a name="utility_methods-questionpath-options"></a>Options
885
886The following options have independent default value that is not affected by [Default Options](#basic_options).
887
888| Option Name | Default Value |
889|-------------------|---------------|
890| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
891| [`limitMessage`](#basic_options-limitmessage) | `'$<error(\n)>Input valid path, please.$<( Min:)min>$<( Max:)max>'` |
892| [`history`](#basic_options-history) | `true` |
893| [`cd`](#basic_options-cd) | `true` |
894
895The following options work as shown in the [Basic Options](#basic_options) section.
896
897<table>
898<tr><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td><td><a href="#basic_options-print"><code>print</code></a></td></tr>
899</table>
900
901And the following additional options are available.
902
903*Note:* It does not check the coherency about a combination of the options as the path requirement. For example, the `{exists: false, isFile: true}` never check that it is a file because it is limited to the path that does not exist.
904
905##### <a name="utility_methods-questionpath-options-exists"></a>`exists`
906
907*Type:* boolean or others
908*Default:* `true`
909
910If `true` is specified, accept only a file or directory path that exists. If `false` is specified, accept only a file or directory path that does *not* exist.
911In any other case, the existence is not checked.
912
913##### <a name="utility_methods-questionpath-options-min_max"></a>`min`, `max`
914
915*Type:* number or others
916*Default:* `undefined`
917
918`min`: A number as a minimum size of the file that is accepted.
919`max`: A number as a maximum size of the file that is accepted.
920If it is not specified or `0` is specified, the size is not checked. (A size of directory is `0`.)
921
922##### <a name="utility_methods-questionpath-options-isfile_isdirectory"></a>`isFile`, `isDirectory`
923
924*Type:* boolean
925*Default:* `false`
926
927`isFile`: If `true` is specified, accept only a file path.
928`isDirectory`: If `true` is specified, accept only a directory path.
929
930##### <a name="utility_methods-questionpath-options-validate"></a>`validate`
931
932*Type:* function or `undefined`
933*Default:* `undefined`
934
935If a function that returns `true` or an error message is specified, call it with a path that was input, and accept the input when the function returned `true`.
936If the function returned a string as an error message, that message is got by the [`error`](#utility_methods-questionpath-additional_placeholders-error) additional [placeholder](#placeholders) parameter.
937A path that was input is parsed before it is passed to the function. `~` is replaced to a home directory, and a path is converted to an absolute path.
938This is also a return value from this method.
939
940For example, accept only PNG file or tell it to the user:
941
942```js
943imageFile = readlineSync.questionPath('Image File :', {
944 validate: function(path) { return /\.png$/i.test(path) || 'It is not PNG'; }
945});
946```
947
948##### <a name="utility_methods-questionpath-options-create"></a>`create`
949
950*Type:* boolean
951*Default:* `false`
952
953If `true` is specified, create a file or directory as a path that was input when it doesn't exist. If `true` is specified to the [`isDirectory`](#utility_methods-questionpath-options-isfile_isdirectory) option, create a directory, otherwise a file.
954It does not affect the existence check. Therefore, you can get a new file or directory path anytime by specifying: `{exists: false, create: true}`
955
956#### <a name="utility_methods-questionpath-additional_placeholders"></a>Additional Placeholders
957
958The following additional [placeholder](#placeholders) parameters are available.
959
960##### <a name="utility_methods-questionpath-additional_placeholders-error"></a>`error`
961
962An error message when the input was not accepted.
963This value is set by readlineSync, or the function that was specified to [`validate`](#utility_methods-questionpath-options-validate) option.
964
965##### <a name="utility_methods-questionpath-additional_placeholders-min_max"></a>`min`, `max`
966
967A current value of [`min` and `max`](#utility_methods-questionpath-options-min_max) option.
968
969### <a name="utility_methods-promptcl"></a>`promptCL`
970
971```js
972argsArray = readlineSync.promptCL([commandHandler[, options]])
973```
974
975Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then consider the input as a command-line and parse it, and then return a result after the Enter key was pressed.
976A return value is an Array that includes the tokens that were parsed. It parses the input from the user as the command-line, and it interprets whitespaces, quotes, etc., and it splits it to tokens properly. Usually, a first element of the Array is command-name, and remaining elements are arguments.
977
978For example:
979
980```js
981argsArray = readlineSync.promptCL();
982console.log(argsArray.join('\n'));
983```
984
985```console
986> command arg "arg" " a r g " "" 'a"r"g' "a""rg" "arg
987command
988arg
989arg
990 a r g
991
992a"r"g
993arg
994arg
995```
996
997#### <a name="utility_methods-promptcl-commandhandler"></a>`commandHandler`
998
999By using the `commandHandler` argument, this method will come into its own. Specifying the Object to this argument has the more merit. And it has the more merit for [`promptCLLoop`](#utility_methods-promptclloop) method.
1000
1001If a function is specified to `commandHandler` argument, it is just called with a parsed Array as an argument list of the function. And `this` is an original input string, in the function.
1002
1003For example, the following 2 codes work same except that `this` is enabled in the second one:
1004
1005```js
1006argsArray = readlineSync.promptCL();
1007if (argsArray[0] === 'add') {
1008 console.log(argsArray[1] + ' is added.');
1009} else if (argsArray[0] === 'copy') {
1010 console.log(argsArray[1] + ' is copied to ' + argsArray[2] + '.');
1011}
1012```
1013
1014```js
1015readlineSync.promptCL(function(command, arg1, arg2) {
1016 console.log('You want to: ' + this); // All of command-line.
1017 if (command === 'add') {
1018 console.log(arg1 + ' is added.');
1019 } else if (command === 'copy') {
1020 console.log(arg1 + ' is copied to ' + arg2 + '.');
1021 }
1022});
1023```
1024
1025If an Object that has properties named as the command-name is specified, the command-name is interpreted, and a function as the value of matched property is called. A function is chosen properly by handling case of the command-name in accordance with the [`caseSensitive`](#basic_options-casesensitive) option.
1026The function is called with a parsed Array that excludes a command-name (i.e. first element is removed from the Array) as an argument list of the function.
1027That is, a structure of the `commandHandler` Object looks like:
1028
1029```js
1030{
1031 commandA: function(arg) { ... }, // commandA requires one argument.
1032 commandB: function(arg1, arg2) { ... }, // readlineSync doesn't care those.
1033 commandC: function() { ... } // Of course, it can also ignore all.
1034}
1035```
1036
1037readlineSync just receives the arguments from the user and passes those to these functions without checking. The functions may have to check whether the required argument was input by the user, and more validate those.
1038
1039For example, the following code works same to the above code:
1040
1041```js
1042readlineSync.promptCL({
1043 add: function(element) { // It's called by also "ADD", "Add", "aDd", etc..
1044 console.log(element + ' is added.');
1045 },
1046 copy: function(from, to) {
1047 console.log(from + ' is copied to ' + to + '.');
1048 }
1049});
1050```
1051
1052If the matched property is not found in the Object, a `_` property is chosen, and the function as the value of this property is called with a parsed Array as an argument list of the function. Note that this includes a command-name. That is, the function looks like `function(command, arg1, arg2, ...) { ... }`.
1053And if the Object doesn't have a `_` property, any command that the matched property is not found in the Object is refused.
1054
1055For example:
1056
1057```js
1058readlineSync.promptCL({
1059 copy: function(from, to) { // command-name is not included.
1060 console.log(from + ' is copied to ' + to + '.');
1061 },
1062 _: function(command) { // command-name is included.
1063 console.log('Sorry, ' + command + ' is not available.');
1064 }
1065});
1066```
1067
1068#### <a name="utility_methods-promptcl-options"></a>Options
1069
1070The following options have independent default value that is not affected by [Default Options](#basic_options).
1071
1072| Option Name | Default Value |
1073|-------------------|---------------|
1074| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
1075| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` |
1076| [`caseSensitive`](#basic_options-casesensitive) | `false` |
1077| [`history`](#basic_options-history) | `true` |
1078
1079The following options work as shown in the [Basic Options](#basic_options) section.
1080
1081<table>
1082<tr><td><a href="#basic_options-prompt"><code>prompt</code></a></td><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td></tr>
1083<tr><td><a href="#basic_options-print"><code>print</code></a></td><td><a href="#basic_options-cd"><code>cd</code></a></td></tr>
1084</table>
1085
1086### <a name="utility_methods-promptloop"></a>`promptLoop`
1087
1088```js
1089readlineSync.promptLoop(inputHandler[, options])
1090```
1091
1092Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then call `inputHandler` function with the input from the user after it has been typed and the Enter key was pressed. Do these repeatedly until `inputHandler` function returns `true`.
1093
1094For example, the following 2 codes work same:
1095
1096```js
1097while (true) {
1098 input = readlineSync.prompt();
1099 console.log('-- You said "' + input + '"');
1100 if (input === 'bye') {
1101 break;
1102 }
1103}
1104console.log('It\'s exited from loop.');
1105```
1106
1107```js
1108readlineSync.promptLoop(function(input) {
1109 console.log('-- You said "' + input + '"');
1110 return input === 'bye';
1111});
1112console.log('It\'s exited from loop.');
1113```
1114
1115```console
1116> hello
1117-- You said "hello"
1118> good morning
1119-- You said "good morning"
1120> bye
1121-- You said "bye"
1122It's exited from loop.
1123```
1124
1125#### <a name="utility_methods-promptloop-options"></a>Options
1126
1127The following options have independent default value that is not affected by [Default Options](#basic_options).
1128
1129| Option Name | Default Value |
1130|-------------------|---------------|
1131| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
1132| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` |
1133| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` |
1134| [`caseSensitive`](#basic_options-casesensitive) | `false` |
1135| [`history`](#basic_options-history) | `true` |
1136
1137The other options work as shown in the [Basic Options](#basic_options) section.
1138
1139### <a name="utility_methods-promptclloop"></a>`promptCLLoop`
1140
1141```js
1142readlineSync.promptCLLoop([commandHandler[, options]])
1143```
1144
1145Execute [`promptCL`](#utility_methods-promptcl) method repeatedly until chosen [`commandHandler`](#utility_methods-promptcl-commandhandler) returns `true`.
1146The [`commandHandler`](#utility_methods-promptcl-commandhandler) may be a function that is called like:
1147
1148```js
1149exit = allCommands(command, arg1, arg2, ...);
1150```
1151
1152or an Object that has the functions that are called like:
1153
1154```js
1155exit = foundCommand(arg1, arg2, ...);
1156```
1157
1158See [`promptCL`](#utility_methods-promptcl) method for details.
1159This method looks like a combination of [`promptCL`](#utility_methods-promptcl) method and [`promptLoop`](#utility_methods-promptloop) method.
1160
1161For example:
1162
1163```js
1164readlineSync.promptCLLoop({
1165 add: function(element) {
1166 console.log(element + ' is added.');
1167 },
1168 copy: function(from, to) {
1169 console.log(from + ' is copied to ' + to + '.');
1170 },
1171 bye: function() { return true; }
1172});
1173console.log('It\'s exited from loop.');
1174```
1175
1176```console
1177> add "New Hard Disk"
1178New Hard Disk is added.
1179> move filesOnOld "New Hard Disk"
1180Requested command is not available.
1181> copy filesOnOld "New Hard Disk"
1182filesOnOld is copied to New Hard Disk.
1183> bye
1184It's exited from loop.
1185```
1186
1187#### <a name="utility_methods-promptclloop-options"></a>Options
1188
1189The following options have independent default value that is not affected by [Default Options](#basic_options).
1190
1191| Option Name | Default Value |
1192|-------------------|---------------|
1193| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
1194| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` |
1195| [`caseSensitive`](#basic_options-casesensitive) | `false` |
1196| [`history`](#basic_options-history) | `true` |
1197
1198The following options work as shown in the [Basic Options](#basic_options) section.
1199
1200<table>
1201<tr><td><a href="#basic_options-prompt"><code>prompt</code></a></td><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-defaultinput"><code>defaultInput</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-buffersize"><code>bufferSize</code></a></td></tr>
1202<tr><td><a href="#basic_options-print"><code>print</code></a></td><td><a href="#basic_options-cd"><code>cd</code></a></td></tr>
1203</table>
1204
1205### <a name="utility_methods-promptsimshell"></a>`promptSimShell`
1206
1207```js
1208input = readlineSync.promptSimShell([options])
1209```
1210
1211Display a prompt-sign that is similar to that of the user's shell to the user, and then return the input from the user after it has been typed and the Enter key was pressed.
1212This method displays a prompt-sign like:
1213
1214On Windows:
1215
1216```shell
1217C:\Users\User\Path\To\Directory>
1218```
1219
1220On others:
1221
1222```shell
1223user@host:~/path/to/directory$
1224```
1225
1226#### <a name="utility_methods-promptsimshell-options"></a>Options
1227
1228The following options have independent default value that is not affected by [Default Options](#basic_options).
1229
1230| Option Name | Default Value |
1231|-------------------|---------------|
1232| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
1233| [`history`](#basic_options-history) | `true` |
1234
1235The other options other than [`prompt`](#basic_options-prompt) option work as shown in the [Basic Options](#basic_options) section.
1236
1237### <a name="utility_methods-keyinyn"></a>`keyInYN`
1238
1239```js
1240boolYesOrEmpty = readlineSync.keyInYN([query[, options]])
1241```
1242
1243Display a `query` to the user if it's specified, and then return a boolean or an empty string immediately a key was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input.
1244This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key:
1245
1246* `Y`: `true`
1247* `N`: `false`
1248* other: `''`
1249
1250The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
1251The default value of `query` is `'Are you sure? :'`.
1252
1253The keys other than `Y` and `N` are also accepted (If you want to know a user's wish explicitly, use [`keyInYNStrict`](#utility_methods-keyinynstrict) method). Therefore, if you let the user make an important decision (e.g. files are removed), check whether the return value is not *falsy*. That is, a default is "No".
1254
1255For example:
1256
1257```js
1258if (!readlineSync.keyInYN('Do you want to install this?')) {
1259 // Key that is not `Y` was pressed.
1260 process.exit();
1261}
1262// Do something...
1263```
1264
1265Or if you let the user stop something that must be done (e.g. something about the security), check whether the return value is `false` explicitly. That is, a default is "Yes".
1266
1267For example:
1268
1269```js
1270// Don't use `(!readlineSync.keyInYN())`.
1271if (readlineSync.keyInYN('Continue virus scan?') === false) {
1272 // `N` key was pressed.
1273 process.exit();
1274}
1275// Continue...
1276```
1277
1278#### <a name="utility_methods-keyinyn-options"></a>Options
1279
1280The following options work as shown in the [Basic Options](#basic_options) section.
1281
1282<table>
1283<tr><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-print"><code>print</code></a></td></tr>
1284</table>
1285
1286And the following additional option is available.
1287
1288##### <a name="utility_methods-keyinyn-options-guide"></a>`guide`
1289
1290*Type:* boolean
1291*Default:* `true`
1292
1293If `true` is specified, a string `'[y/n]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added.
1294
1295For example:
1296
1297```js
1298readlineSync.keyInYN('Do you like me?'); // No colon
1299readlineSync.keyInYN('Really? :'); // Colon already exists
1300```
1301
1302``` console
1303Do you like me? [y/n] :y
1304Really? [y/n] :y
1305```
1306
1307### <a name="utility_methods-keyinynstrict"></a>`keyInYNStrict`
1308
1309```js
1310boolYes = readlineSync.keyInYNStrict([query[, options]])
1311```
1312
1313Display a `query` to the user if it's specified, and then accept only `Y` or `N` key, and then return a boolean immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input.
1314This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key:
1315
1316* `Y`: `true`
1317* `N`: `false`
1318
1319The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
1320The default value of `query` is `'Are you sure? :'`.
1321
1322A key other than `Y` and `N` is not accepted. That is, a return value has no default. Therefore, the user has to tell an own wish explicitly. If you want to know a user's wish easily, use [`keyInYN`](#utility_methods-keyinyn) method.
1323
1324This method works same to [`keyInYN`](#utility_methods-keyinyn) method except that this accept only `Y` or `N` key (Therefore, a return value is boolean every time). The options also work same to [`keyInYN`](#utility_methods-keyinyn) method.
1325
1326### <a name="utility_methods-keyinpause"></a>`keyInPause`
1327
1328```js
1329readlineSync.keyInPause([query[, options]])
1330```
1331
1332Display a `query` to the user if it's specified, and then just wait for a key to be pressed by the user.
1333This method works like the `window.alert` method of web browsers. This is used to make the running of script pause and show something to the user, or wait for the user to be ready.
1334By default, any key is accepted. You can change this behavior by specifying [`limit`](#basic_options-limit) option (e.g. accept only a Space Bar).
1335
1336The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
1337The default value of `query` is `'Continue...'`.
1338
1339For example:
1340
1341```js
1342// Have made the preparations for something...
1343console.log('==== Information of Your Computer ====');
1344console.log(info); // This can be `query`.
1345readlineSync.keyInPause();
1346console.log('It\'s executing now...');
1347// Do something...
1348```
1349
1350```console
1351==== Information of Your Computer ====
1352FOO: 123456
1353BAR: abcdef
1354Continue... (Hit any key)
1355It's executing now...
1356```
1357
1358#### <a name="utility_methods-keyinpause-options"></a>Options
1359
1360The following option has independent default value that is not affected by [Default Options](#basic_options).
1361
1362| Option Name | Default Value |
1363|-------------------|---------------|
1364| [`limit`](#basic_options-limit) | `null` |
1365
1366The following options work as shown in the [Basic Options](#basic_options) section.
1367
1368<table>
1369<tr><td><a href="#basic_options-casesensitive"><code>caseSensitive</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-print"><code>print</code></a></td></tr>
1370</table>
1371
1372And the following additional option is available.
1373
1374##### <a name="utility_methods-keyinpause-options-guide"></a>`guide`
1375
1376*Type:* boolean
1377*Default:* `true`
1378
1379If `true` is specified, a string `'(Hit any key)'` as guide for the user is added to `query`.
1380
1381For example:
1382
1383```js
1384readlineSync.keyInPause('It\'s pausing now...');
1385```
1386
1387``` console
1388It's pausing now... (Hit any key)
1389```
1390
1391### <a name="utility_methods-keyinselect"></a>`keyInSelect`
1392
1393```js
1394index = readlineSync.keyInSelect(items[, query[, options]])
1395```
1396
1397Display the list that was created with the `items` Array, and the `query` to the user if it's specified, and then return the number as an index of the `items` Array immediately it was chosen by pressing a key by the user, **without pressing the Enter key**. Note that the user has no chance to change the input.
1398
1399The `query` is handled the same as that of the [`question`](#basic_methods-question) method.
1400The default value of `query` is `'Choose one from list :'`.
1401
1402The minimum length of `items` Array is 1 and maximum length is 35. These elements are displayed as item list. A key to let the user choose an item is assigned to each item automatically in sequence like "1, 2, 3 ... 9, A, B, C ...". A number as an index of the `items` Array that corresponds to a chosen item by the user is returned.
1403
1404For example:
1405
1406```js
1407frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive'];
1408index = readlineSync.keyInSelect(frameworks, 'Which framework?');
1409console.log(frameworks[index] + ' is enabled.');
1410```
1411
1412```console
1413[1] Express
1414[2] hapi
1415[3] flatiron
1416[4] MEAN.JS
1417[5] locomotive
1418[0] CANCEL
1419
1420Which framework? [1...5 / 0] :2
1421hapi is enabled.
1422```
1423
1424#### <a name="utility_methods-keyinselect-options"></a>Options
1425
1426The following option has independent default value that is not affected by [Default Options](#basic_options).
1427
1428| Option Name | Default Value |
1429|-------------------|---------------|
1430| [`hideEchoBack`](#basic_options-hideechoback) | `false` |
1431
1432The following options work as shown in the [Basic Options](#basic_options) section.
1433
1434<table>
1435<tr><td><a href="#basic_options-mask"><code>mask</code></a></td><td><a href="#basic_options-encoding"><code>encoding</code></a></td><td><a href="#basic_options-print"><code>print</code></a></td></tr>
1436</table>
1437
1438And the following additional options are available.
1439
1440##### <a name="utility_methods-keyinselect-options-guide"></a>`guide`
1441
1442*Type:* boolean
1443*Default:* `true`
1444
1445If `true` is specified, a string like `'[1...5]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. This is the key list that corresponds to the item list.
1446
1447##### <a name="utility_methods-keyinselect-options-cancel"></a>`cancel`
1448
1449*Type:* boolean, string or others
1450*Default:* `'CANCEL'`
1451
1452If a value other than `false` is specified, an item to let the user tell "cancel" is added to the item list. "[0] CANCEL" (default) is displayed, and if `0` key is pressed, `-1` is returned.
1453You can specify a label of this item other than `'CANCEL'`. A string such as `'Go back'` (empty string `''` also), something that is converted to string such as `Date`, a string that includes [placeholder](#placeholders) such as `'Next $<itemsCount> items'` are accepted.
1454
1455#### <a name="utility_methods-keyinselect-additional_placeholders"></a>Additional Placeholders
1456
1457The following additional [placeholder](#placeholders) parameters are available.
1458
1459##### <a name="utility_methods-keyinselect-additional_placeholders-itemscount"></a>`itemsCount`
1460
1461A length of a current `items` Array.
1462
1463For example:
1464
1465```js
1466items = ['item-A', 'item-B', 'item-C', 'item-D', 'item-E'];
1467index = readlineSync.keyInSelect(items, null,
1468 {cancel: 'Show more items than $<itemsCount>'});
1469```
1470
1471```console
1472[1] item-A
1473[2] item-B
1474[3] item-C
1475[4] item-D
1476[5] item-E
1477[0] Show more items than 5
1478```
1479
1480##### <a name="utility_methods-keyinselect-additional_placeholders-firstitem"></a>`firstItem`
1481
1482A first item in a current `items` Array.
1483
1484For example:
1485
1486```js
1487index = readlineSync.keyInSelect(items, 'Choose $<firstItem> or another :');
1488```
1489
1490##### <a name="utility_methods-keyinselect-additional_placeholders-lastitem"></a>`lastItem`
1491
1492A last item in a current `items` Array.
1493
1494For example:
1495
1496```js
1497items = ['January', 'February', 'March', 'April', 'May', 'June'];
1498index = readlineSync.keyInSelect(items, null,
1499 {cancel: 'In after $<lastItem>'});
1500```
1501
1502```console
1503[1] January
1504[2] February
1505[3] March
1506[4] April
1507[5] May
1508[6] June
1509[0] In after June
1510```
1511
1512## <a name="placeholders"></a>Placeholders
1513
1514[`hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue`](#placeholders-parameters-hideechoback_mask_defaultinput_casesensitive_keepwhitespace_encoding_buffersize_history_cd_limit_truevalue_falsevalue), [`limitCount`, `limitCountNotZero`](#placeholders-parameters-limitcount_limitcountnotzero), [`lastInput`](#placeholders-parameters-lastinput), [`history_mN`](#placeholders-parameters-historymn), [`cwd`, `CWD`, `cwdHome`](#placeholders-parameters-cwd_cwd_cwdhome), [`date`, `time`, `localeDate`, `localeTime`](#placeholders-parameters-date_time_localedate_localetime), [`C1-C2`](#placeholders-parameters-c1_c2)
1515
1516The placeholders in the text are replaced to another string.
1517
1518For example, the [`limitMessage`](#basic_options-limitmessage) option to display a warning message that means that the command the user requested is not available:
1519
1520```js
1521command = readlineSync.prompt({
1522 limit: ['add', 'remove'],
1523 limitMessage: '$<lastInput> is not available.'
1524});
1525```
1526
1527```console
1528> delete
1529delete is not available.
1530```
1531
1532The placeholders can be included in:
1533
1534* `query` argument
1535* [`prompt`](#basic_options-prompt) and [`limitMessage`](#basic_options-limitmessage) options
1536* [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method ([`C1-C2`](#placeholders-parameters-c1_c2) parameter only)
1537* And some additional options for the [Utility Methods](#utility_methods).
1538
1539### <a name="placeholders-syntax"></a>Syntax
1540
1541```
1542$<parameter>
1543```
1544
1545Or
1546
1547```
1548$<(text1)parameter(text2)>
1549```
1550
1551The placeholder is replaced to a string that is got by a `parameter`.
1552Both the `(text1)` and `(text2)` are optional.
1553A more added `'$'` at the left of the placeholder is used as an escape character, it disables a placeholder. For example, `'$$<foo>'` is replaced to `'$<foo>'`. If you want to put a `'$'` which is *not* an escape character at the left of a placeholder, specify it like `'$<($)bufferSize>'`, then it is replaced to `'$1024'`.
1554
1555At the each position of `'(text1)'` and `'(text2)'`, `'text1'` and `'text2'` are put when a string that was got by a `parameter` has length more than 0. If that got string is `''`, a placeholder with or without `'(text1)'` and `'(text2)'` is replaced to `''`.
1556
1557For example, a warning message that means that the command the user requested is not available:
1558
1559```js
1560command = readlineSync.prompt({
1561 limit: ['add', 'remove'],
1562 limitMessage: 'Refused $<lastInput> you requested. Please input another.'
1563});
1564```
1565
1566```console
1567> give-me-car
1568Refused give-me-car you requested. Please input another.
1569```
1570
1571It looks like no problem.
1572But when the user input nothing (hit only the Enter key), and then a message is displayed:
1573
1574```console
1575>
1576Refused you requested. Please input another.
1577```
1578
1579This goes well:
1580
1581```js
1582command = readlineSync.prompt({
1583 limit: ['add', 'remove'],
1584 limitMessage: 'Refused $<lastInput( you requested)>. Please input another.'
1585});
1586```
1587
1588```console
1589>
1590Refused . Please input another.
1591```
1592
1593(May be more better: `'$<(Refused )lastInput( you requested. )>Please input another.'`)
1594
1595*Note:* The syntax `${parameter}` of older version is still supported, but this should not be used because it may be confused with template string syntax of ES6. And this will not be supported in due course of time.
1596
1597### <a name="placeholders-parameters"></a>Parameters
1598
1599The following parameters are available. And some additional parameters are available in the [Utility Methods](#utility_methods).
1600
1601#### <a name="placeholders-parameters-hideechoback_mask_defaultinput_casesensitive_keepwhitespace_encoding_buffersize_history_cd_limit_truevalue_falsevalue"></a>`hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue`
1602
1603A current value of each option.
1604It is converted to human readable if possible. The boolean value is replaced to `'on'` or `'off'`, and the Array is replaced to the list of only string and number elements.
1605And in the `keyIn*` method, the parts of the list as characters sequence are suppressed. For example, when `['a', 'b', 'c', 'd', 'e']` is specified to the [`limit`](#basic_options-limit) option, `'$<limit>'` is replaced to `'a...e'`. If `true` is specified to the [`caseSensitive`](#basic_options-casesensitive) option, the characters are converted to lower case.
1606
1607For example:
1608
1609```js
1610input = readlineSync.question(
1611 'Input something or the Enter key as "$<defaultInput>" :',
1612 {defaultInput: 'hello'}
1613);
1614```
1615
1616```console
1617Input something or the Enter key as "hello" :
1618```
1619
1620#### <a name="placeholders-parameters-limitcount_limitcountnotzero"></a>`limitCount`, `limitCountNotZero`
1621
1622A length of a current value of the [`limit`](#basic_options-limit) option.
1623When the value of the [`limit`](#basic_options-limit) option is empty, `'$<limitCount>'` is replaced to `'0'`, `'$<limitCountNotZero>'` is replaced to `''`.
1624
1625For example:
1626
1627```js
1628action = readlineSync.question(
1629 'Choose action$<( from )limitCountNotZero( actions)> :',
1630 {limit: availableActions}
1631);
1632```
1633
1634```console
1635Choose action from 5 actions :
1636```
1637
1638#### <a name="placeholders-parameters-lastinput"></a>`lastInput`
1639
1640A last input from the user.
1641In any case, this is saved.
1642
1643For example:
1644
1645```js
1646command = readlineSync.prompt({
1647 limit: availableCommands,
1648 limitMessage: '$<lastInput> is not available.'
1649});
1650```
1651
1652```console
1653> wrong-command
1654wrong-command is not available.
1655```
1656
1657#### <a name="placeholders-parameters-historymn"></a>`history_mN`
1658
1659When the history expansion feature is enabled (see [`history`](#basic_options-history) option), a current command line minus `N`.
1660*This feature keeps the previous input only.* That is, only `history_m1` is supported.
1661
1662For example:
1663
1664```js
1665while (true) {
1666 input = readlineSync.question('Something$<( or "!!" as ")history_m1(")> :');
1667 console.log('-- You said "' + input + '"');
1668}
1669```
1670
1671```console
1672Something :hello
1673-- You said "hello"
1674Something or "!!" as "hello" :!!
1675hello
1676-- You said "hello"
1677```
1678
1679#### <a name="placeholders-parameters-cwd_cwd_cwdhome"></a>`cwd`, `CWD`, `cwdHome`
1680
1681A current working directory.
1682
1683* `cwd`: A full-path
1684* `CWD`: A directory name
1685* `cwdHome`: A path that includes `~` as the home directory
1686
1687For example, like bash/zsh:
1688
1689```js
1690command = readlineSync.prompt({prompt: '[$<cwdHome>]$ '});
1691```
1692
1693```console
1694[~/foo/bar]$
1695```
1696
1697#### <a name="placeholders-parameters-date_time_localedate_localetime"></a>`date`, `time`, `localeDate`, `localeTime`
1698
1699A string as current date or time.
1700
1701* `date`: A date portion
1702* `time`: A time portion
1703* `localeDate`: A locality sensitive representation of the date portion based on system settings
1704* `localeTime`: A locality sensitive representation of the time portion based on system settings
1705
1706For example:
1707
1708```js
1709command = readlineSync.prompt({prompt: '[$<localeDate>]> '});
1710```
1711
1712```console
1713[04/21/2015]>
1714```
1715
1716#### <a name="placeholders-parameters-c1_c2"></a>`C1-C2`
1717
1718_For [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method only_
1719
1720A character list.
1721`C1` and `C2` are each single character as the start and the end. A sequence in ascending or descending order of characters ranging from `C1` to `C2` is created. For example, `'$<a-e>'` is replaced to `'abcde'`. `'$<5-1>'` is replaced to `'54321'`.
1722
1723For example, let the user input a password that is created with alphabet:
1724
1725```js
1726password = readlineSync.questionNewPassword('PASSWORD :', {charlist: '$<a-z>'});
1727```
1728
1729See also [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method).
1730
1731## <a name="with_task_runner"></a>With Task Runner
1732
1733The easy way to control a flow of the task runner by the input from the user:
1734
1735* [Grunt](http://gruntjs.com/) plugin: [grunt-confirm](https://github.com/anseki/grunt-confirm)
1736* [gulp](http://gulpjs.com/) plugin: [gulp-confirm](https://github.com/anseki/gulp-confirm)
1737
1738If you want to control a flow of the task runner (e.g. [Grunt](http://gruntjs.com/)), call readlineSync in a task callback that is called by the task runner. Then a flow of tasks is paused and it is controlled by the user.
1739
1740For example, by using [grunt-task-helper](https://github.com/anseki/grunt-task-helper):
1741
1742```console
1743$ grunt
1744Running "fileCopy" task
1745Files already exist:
1746 file-a.png
1747 file-b.js
1748Overwrite? [y/n] :y
1749file-a.png copied.
1750file-b.js copied.
1751Done.
1752```
1753
1754`Gruntfile.js`
1755
1756```js
1757grunt.initConfig({
1758 taskHelper: {
1759 fileCopy: {
1760 options: {
1761 handlerByTask: function() {
1762 // Abort the task if user don't want it.
1763 return readlineSync.keyInYN('Overwrite?');
1764 },
1765 filesArray: []
1766 },
1767 ...
1768 }
1769 },
1770 copy: {
1771 fileCopy: {
1772 files: '<%= taskHelper.fileCopy.options.filesArray %>'
1773 }
1774 }
1775});
1776```
1777
1778## <a name="note"></a>Note
1779
1780### <a name="note-platforms"></a>Platforms
1781
1782TTY interfaces are different by the platforms. If the platform doesn't support the interactively reading from TTY, an error is thrown.
1783
1784```js
1785try {
1786 answer = readlineSync.question('What is your favorite food? :');
1787} catch (e) {
1788 console.error(e);
1789 process.exit(1);
1790}
1791```
1792
1793### <a name="note-platforms"></a>Control characters
1794
1795TTY interfaces are different by the platforms. In some environments, ANSI escape sequences might be ignored. For example, in non-POSIX TTY such as Windows CMD does not support it (that of Windows 8 especially has problems). Since readlineSync does not use Node.js library that emulates POSIX TTY (but that is still incomplete), those characters may be not parsed. Then, using ANSI escape sequences is not recommended if you will support more environments.
1796Also, control characters user input might be not accepted or parsed. That behavior differs depending on the environment. And current Node.js does not support controlling a readline system library.
1797
1798### <a name="note-reading_by_external_program"></a>Reading by external program
1799
1800readlineSync tries to read from a console by using the external program if it is needed (e.g. when the input stream is redirected on Windows XP). And if the running Node.js doesn't support the [Synchronous Process Execution](http://nodejs.org/api/child_process.html#child_process_synchronous_process_creation) (i.e. Node.js v0.10-), readlineSync uses "piping via files" for the synchronous execution.
1801As everyone knows, "piping via files" is no good. It blocks the event loop and a process. It might make the your script be slow.
1802
1803Why did I choose it? :
1804
1805* Good modules (native addon) for the synchronous execution exist, but node-gyp can't compile those in some platforms or Node.js versions.
1806* I think that the security is important more than the speed. Some modules have problem about security. Those don't protect the data. I think that the speed is not needed usually, because readlineSync is used while user types keys.
1807
1808## <a name="deprecated_methods_and_options"></a>Deprecated methods and options
1809
1810See [README-Deprecated.md](README-Deprecated.md).