readlineSync 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`.
These 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.
You can specify `options` (see [Options](#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`](#hideEchoBack) option.**
The `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.
And it can include the [placeholders](#placeholders).
Display the prompt-sign (see [`prompt`](#options-prompt) option) to the user, and then return the input from the user after it has been typed and an Enter key was pressed.
Display the `query` to the user if it's specified, and then return the character as the key immediately it was pressed by the user, **without pressing an Enter key**. Note that the user has no chance to change the input.
You can specify `options` (see [Options](#options)) to control the behavior (e.g. ignoring keys except some keys, checking target key, etc.).
The `query` is handled the same as that of the [`question`](#question) method.
An `options` Object can be specified to the methods to control the behavior of readlineSync. The options that were not specified are got from the Default Options. You can change the Default Options by [`setDefaultOptions`](#setdefaultoptions) method anytime, and it is kept until a current process is exited.
Specify the options that are often used to the Default Options, and specify temporary options to the methods.
Set the prompt-sign that is displayed to the user by `prompt*` methods. For example you see `> ` that is Node's prompt-sign when you run `node` on the command line.
This 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 every time.
And it can include the [placeholders](#placeholders).
Set the mask characters that are shown instead of the secret text (e.g. password) when [`hideEchoBack`](#hideEchoBack) option is `true`. If you want to show nothing, specify `''`. (But it might be not user friendly in some cases.)
*Note:* In some cases (e.g. when the input stream is redirected on Windows XP), `'*'` or `''` might be used always.
Specify the characters as the key. All strings or Array of those are decomposed into single characters. For example, `'abcde'` is the same as `['a', 'b', 'c', 'd', 'e']` or `['a', 'bc', ['d', 'e']]`.
By default, compare the strings in case-insensitive mode (i.e. `a` equals `A`). If `true` is specified, compare in case-sensitive mode, don't ignore case (i.e. `a` is different from `A`).
It have an effect on: [`limit`](#limit), [`trueValue`](#trueValue), [`falseValue`](#falseValue), some [placeholders](#placeholders), and some [Utility Methods](#utility-methods).
When readlineSync reads from a console directly (without external program), use a size `bufferSize` buffer.
Even 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.
* Like `your-script >foo.log`, when the output stream is redirected to record those into a file, this is used to output the conversation to the file. That is, the conversation isn't outputted to `foo.log` without this code.
readlineSync supports a changing the current working directory feature that is similar to the `cd` in shell. If `true` is specified, enable this feature.
This helps the user when you let the user input the multiple local files.
The `query` is handled the same as that of the [`question`](#question) method.
The default value of `query` is `'Input e-mail address :'`.
*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, spefify [`limit`](#limit) option.
Display the `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 an Enter key was pressed.
The `query` is handled the same as that of the [`question`](#question) method.
The default value of `query` is `'Input new password :'`.
*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.
And the following additional options are available.
##### `charlist`
**Type:** string
**Default:** `'${!-~}'`
A 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.
The [placeholders](#placeholders) like `'${a-e}'` are replaced to the characters like `'abcde'`.
##### `min`, `max`
**Type:** number
**Default:** `min`: `12`, `max`: `24`
`min`: A number as a minimum length of the password.
`max`: A number as a maximum length of the password.
Display the `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 an Enter key was pressed.
This parses the input as possible by `parseInt()`. For example, it interprets `' 5 '`, `'5.6'`, `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`.
The `query` is handled the same as that of the [`question`](#question) method.
#### Options
The following options have independent default value. It is not affected by [Default Options](#options).
Display the `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 an Enter key was pressed.
This parses the input as possible by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`.
The `query` is handled the same as that of the [`question`](#question) method.
#### Options
The following options have independent default value. It is not affected by [Default Options](#options).
Display the `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 an Enter key was pressed.
The path can include `~` as the home directory.
You 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.
It is recommended to use this method with the [`cd`](#cd) option. (Default: `true`)
The `query` is handled the same as that of the [`question`](#question) method.
The default value of `query` is `'Input path (you can "cd" and "pwd") :'`.
And the following additional options are available.
*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.
If `true` is specified, only a file or directory path that exists is accepted. If `false` is specified, only a file or directory path that does *not* exist is accepted. In any other case, the existence is not checked.
`min`: A number as a minimum size of the file that is accepted.
`max`: A number as a maximum size of the file that is accepted.
If it is not specified or `0` is specified, the size is not checked. (A size of directory is `0`.)
##### `isFile`, `isDirectory`
**Type:** boolean
**Default:** `false`
`isFile`: If `true` is specified, only a file path is accepted.
`isDirectory`: If `true` is specified, only a directory path is accepted.
##### `validate`
**Type:** function or `undefined`
**Default:** `undefined`
If a function is specified, call it with a path that was input, and the input is accepted when it returned `true`.
A 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.
This is also a return value from this method.
##### `create`
**Type:** boolean
**Default:** `false`
If `true` is specified, create a file or directory as the specified path when it doesn't exist. If `true` is specified to the [`isDirectory`](#isdirectory) option, create a directory, otherwise a file.
It does not affect the existence check. Therefore, you can get a new file or directory path anytime by specifying: `{exists: false, create: true}`.
Display the prompt-sign (see [`prompt`](#options-prompt) option) to the user, and then consider the input as a command-line and parse it, and then return a result after an Enter key was pressed.
A 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.
> command arg "arg" " a r g " "" 'a"r"g' "a""rg" "arg
command
arg
arg
a r g
a"r"g
arg
arg
```
#### `commandHandler`
By 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`](#promptclloop) method.
If a function is specified to `commandHandler`, it is just called with a parsed Array as an argument list of the function. And `this` is a original input string, in the function.
For example: The following 2 codes work same except that `this` is enabled in the second one.
```js
argsArray = readlineSync.promptCL();
if (argsArray[0] === 'add') {
console.log(argsArray[1] + ' is added.');
} else if (argsArray[0] === 'copy') {
console.log(argsArray[1] + ' is copied to ' + argsArray[2] + '.');
console.log('You want to: ' + this); // All of command-line.
if (command === 'add') {
console.log(arg1 + ' is added.');
} else if (command === 'copy') {
console.log(arg1 + ' is copied to ' + arg2 + '.');
}
});
```
If 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`](#casesensitive) option.
The 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.
That is, a structure of the `commandHandler` Object looks like:
```js
{
commandA: function(arg) { ... }, // commandA requires one argument.
commandC: function() { ... } // Of course, it can also ignore all.
}
```
readlineSync 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.
For example: The following code works same to the above code.
```js
readlineSync.promptCL({
add: function(element) { // It's called by also "ADD", "Add", "aDd", etc..
console.log(element + ' is added.');
},
copy: function(from, to) {
console.log(from + ' is copied to ' + to + '.');
}
});
```
If 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, ...) { ... }`.
Display the prompt-sign (see [`prompt`](#options-prompt) option) to the user, and then call `inputHandler` function with the input from the user after it has been typed and an Enter key was pressed. Do these repeatedly until `inputHandler` function returns `true`.
Display the 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 an Enter key was pressed.
Display the `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 an Enter key**. Note that the user has no chance to change the input.
This 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:
*`Y`: `true`
*`N`: `false`
* other: `''`
The `query` is handled the same as that of the [`question`](#question) method.
The default value of `query` is `'Are you sure? :'`.
A key other than `Y` and `N` is also accepted (If you want to know a user's wish explicitly, use [`keyInYNStrict`](#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".
For example:
```js
if (!readlineSync.keyInYN('Do you want to install this?')) {
// Key that is not `Y` was pressed.
process.exit();
}
// Do something...
```
Or 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".
For example:
```js
// Don't use `(!readlineSync.keyInYN())`.
if (readlineSync.keyInYN('Continue virus scan?') === false) {
Display the `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 an Enter key**. Note that the user has no chance to change the input.
This 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:
A key other than `Y` and `N` is not accepted. That is, this method 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`](#keyinyn) method.
This method works same to [`keyInYN`](#keyinyn) method except that this accept only `Y` or `N` key. The options also work same to [`keyInYN`](#keyinyn) method.
### `keyInPause`
```js
readlineSync.keyInPause([query[, options]])
```
Display the `query` to the user if it's specified, and then just wait for a key to be pressed by the user.
This 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.
By default, any key is accepted. You can change this behavior by specifying [`limit`](#limit) option (e.g. accept only a Space Bar).
The `query` is handled the same as that of the [`question`](#question) method.
The default value of `query` is `'Continue...'`.
For example:
```js
// Have made the preparations for something...
console.log('==== Informations of Your Computer ====');
console.log(info); // This can be `query`.
readlineSync.keyInPause();
console.log('It\'s executing now...');
// Do something...
```
```console
==== Informations of Your Computer ====
FOO: 123456
BAR: abcdef
Continue... (Hit any key)
It's executing now...
```
#### Options
The following options have independent default value. It is not affected by [Default Options](#options).
| Option Name | Default Value |
|-------------------|---------------|
| [`limit`](#limit) | `null` |
The following options work as shown in the [Options](#options) section.
Display 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 an Enter key**. Note that the user has no chance to change the input.
The default value of `query` is `'Choose one from list :'`.
The 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 a 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.
If `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.
If `true` is specified, an item to let the user tell "cancel" is added to the item list. "[0] CANCEL" is displayed, and if `0` key is pressed, `-1` is returned.
The placeholders in the text are replaced to another string.
For example, the [`limitMessage`](#limitmessage) option to display a warning message that means that the command the user requested is not available:
```js
command = readlineSync.prompt({
limit: ['add', 'remove'],
limitMessage: '${lastInput} is not available.'
});
```
```console
> delete
delete is not available.
```
The placeholders can be included in:
*`query` argument
* [`prompt`](#options-prompt) and [`limitMessage`](#limitmessage) options
* [`limit` option for `keyIn*` method](#for-keyin-method) and [`charlist`](#charlist) option for [`questionNewPassword`](#questionnewpassword) method ([`C1-C2`](#c1-c2) parameter only)
And some options for the [Utility Methods](#utility-methods).
### Syntax
```
${parameter}
```
Or
```
${(text1)parameter(text2)}
```
The placeholder is replaced to a string that is got by a `parameter`.
Both the `(text1)` and `(text2)` are optional.
A more added `$` at 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 `$` that is not an escape character at left of a placeholder, spefify it like `${($)bufferSize}`, then it is replaced to `$1024`.
`(text1)` and `(text2)` are replaced to `text1` and `text2` when a string that was got by a `parameter` has length more than 0. If that string is `''`, a placeholder that includes `(text1)` and `(text2)` is replaced to `''`.
For example, a warning message that means that the command the user requested is not available:
```js
command = readlineSync.prompt({
limit: ['add', 'remove'],
limitMessage: 'Refused ${lastInput} you requested. Please input another.'
});
```
```console
> give-me-car
Refused give-me-car you requested. Please input another.
```
It looks like no problem.
But when the user input nothing (hit only Enter key), and then a message is displayed:
```console
>
Refused you requested. Please input another.
```
This goes well:
```js
command = readlineSync.prompt({
limit: ['add', 'remove'],
limitMessage: 'Refused ${lastInput( you requested)}. Please input another.'
});
```
```console
>
Refused . Please input another.
```
(`${(Refused )lastInput( you requested. )}Please input another.` may be more better.)
### Parameters
The following parameters are available. And some additional parameters are available in the [Utility Methods](#utility-methods).
It is converted to human readable as possible. The boolean value is replaced to `'on'` or `'off'`, and the Array is replaced to the list of only string and number.
And in the `keyIn*` method, the sequence parts of that list as key characters are suppressed. For example, when `['a', 'b', 'c', 'd', 'e']` is specified to the [`limit`](#limit) option, `${limit}` is replaced to `'a...e'`. If `true` is specified to the [`caseSensitive`](#casesensitive) option, the characters are converted to lower case.
For example:
```js
input = readlineSync.question('Something, or Enter key as "${defaultInput}" :', {
defaultInput: 'hello'
});
```
```console
Something, or Enter key as "hello" :
```
#### `limitCount`, `limitCountNotZero`
A length of a current value of the [`limit`](#limit) option.
`limitCountNotZero` is replaced to `''` when the value of the [`limit`](#limit) option is empty.
For example:
```js
command = readlineSync.prompt({
limit: availableCommands,
// Don't need `limitCountNotZero`
// because if `limit` is empty (i.e. it's not limited),
// `limitMessage` is never displayed.
limitMessage: '${(You can use )limitCount( commands only.)}'
});
```
```console
> wrong-command
You can use 5 commands only.
```
#### `lastInput`
A last input from the user.
In any case, this is saved.
For example:
```js
command = readlineSync.prompt({
limit: availableCommands,
limitMessage: '${lastInput} is not available.'
});
```
```console
> wrong-command
wrong-command is not available.
```
#### `history_mN`
When the history expansion feature is enabled (see [`history`](#history) option), a current command line minus `N`.
*This feature keeps the previous input only.* That is, only `history_m1` is supported.
For example:
```js
while (true) {
input = readlineSync.question('Something${(, or "!!" as ")history_m1(")} :');
console.log('-- You said "' + input + '"');
}
```
```console
Something :hello
-- You said "hello"
Something, or "!!" as "hello" :!!
-- You said "hello"
```
#### `cwd`, `CWD`, `cwdHome`
A current working directory.
*`cwd`: A full-path
*`CWD`: A directory name
*`cwdHome`: A path that includes `~` as the home directory
*For [`limit` option for `keyIn*` method](#for-keyin-method) and [`charlist`](#charlist) option for [`questionNewPassword`](#questionnewpassword) method only*
A character list.
`C1` and `C2` are a single character as the start and the end. A sequence of characters from `C1` to `C2` in ascending or descending order is created. For example, `a-e` is replaced to `'abcde'`. `5-1` is replaced to `'54321'`.
For example, let the user input a password that is created with alphabet:
If you want to control the flow of task runner (e.g. [Grunt](http://gruntjs.com/)), call readlineSync in a task callback that is called by task runner. Then the flow of tasks is paused and it is controlled by the user.
readlineSync 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 doesn't support the [Synchronous Process Execution](http://nodejs.org/api/child_process.html#child_process_synchronous_process_creation) (i.e. Node v0.10-), readlineSync uses "piping via files" for the synchronous execution.
As everyone knows, "piping via files" is no good. It blocks the event loop and a process. It may make a your script be slow.
* The good modules (native addon) for the synchronous execution exist, but node-gyp can't compile those in some platforms or Node versions.
* 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 the user types keys.
## Deprecated Methods and Options
The readlineSync current version is fully compatible with older version.