readline-sync/README.md

311 lines
9.8 KiB
Markdown
Raw Normal View History

2013-08-29 19:26:22 +02:00
# readlineSync
2013-08-29 12:55:23 +02:00
Synchronous [Readline](http://nodejs.org/api/readline.html) for interactively running to have a conversation with the user via a console(TTY).
2013-08-29 12:55:23 +02:00
2015-04-13 08:55:33 +02:00
readlineSync tries to let your script have a conversation with the user via a console, even when the input/output is redirected like `your-script <foo.dat >bar.log`.
2013-08-29 12:55:23 +02:00
## Example
```js
var readlineSync = require('readline-sync');
2015-01-26 17:11:25 +01:00
var userName = readlineSync.question('May I have your name? :'); // Wait for user's response.
var favFood = readlineSync.question('Hi ' + userName + '! What is your favorite food? :');
console.log('Oh, ' + userName + ' likes ' + favFood + '!');
```
```console
May I have your name? :CookieMonster
Hi CookieMonster! What is your favorite food? :tofu
Oh, CookieMonster likes tofu!
```
```js
var readlineSync = require('readline-sync');
// The user does not have to press an Enter key.
if (readlineSync.keyInYN('Do you want this module?')) {
// 'Y' key was pressed.
installModule();
} else {
searchAnother();
}
2013-08-29 12:55:23 +02:00
```
## Installation
```shell
npm install readline-sync
2013-08-29 12:55:23 +02:00
```
## Input Methods
2013-08-29 12:55:23 +02:00
2015-01-26 21:01:05 +01:00
### question
2013-08-29 19:26:22 +02:00
```js
answer = readlineSync.question([query[, options]])
2013-08-29 19:26:22 +02:00
```
Display the `query` to the user, and then return the user's response after it has been typed and Enter key was pressed.
2015-03-12 03:03:04 +01:00
You can specify `options` (see [Options](#options)). **If the user inputs the secret text (e.g. password), you should consider `noEchoBack` option.**
2015-01-26 17:11:25 +01:00
2015-02-22 12:57:07 +01:00
The `query` may be string, or may not be (e.g. number, Date, Object, etc.). This is converted to string (i.e. `toString` method is called) before it is displayed.
2015-01-26 17:11:25 +01:00
2015-01-26 21:01:05 +01:00
### prompt
2013-08-29 19:26:22 +02:00
```js
input = readlineSync.prompt([options])
2013-08-29 19:26:22 +02:00
```
Display the current prompt (see [setPrompt](#setprompt) method) to the user, and then return the user's response after it has been typed and Enter key was pressed.
2015-03-12 03:03:04 +01:00
You can specify `options` (see [Options](#options)). **If the user inputs the secret text (e.g. password), you should consider `noEchoBack` option.**
2015-01-26 17:11:25 +01:00
### keyIn
```js
pressedKey = readlineSync.keyIn([query[, options]])
```
Display the `query` to the user, and then return the character as the pressed key by the user, **without pressing the Enter key**.
You can specify `options` (see [Options](#options)).
Note that the user has no chance to change the input.
The `query` may be string, or may not be (e.g. number, Date, Object, etc.). This is converted to string (i.e. `toString` method is called) before it is displayed.
## Setting Methods
2015-01-26 21:01:05 +01:00
### setPrompt
2013-08-29 19:26:22 +02:00
```js
currentPrompt = readlineSync.setPrompt([newPrompt])
2013-08-29 19:26:22 +02:00
```
Set the prompt, for example when you run `node` on the command line, you see `> `, which is Node's prompt. The default is `'> '`. (see [prompt](#prompt) method)
2015-01-26 17:11:25 +01:00
2015-03-20 12:34:18 +01:00
The `newPrompt` may be string, or may not be (e.g. number, Date, Object, etc.). This is converted to string (i.e. `toString` method is called) before it is displayed every time.
2015-01-26 17:11:25 +01:00
For example, `[foo-directory]#` like a bash shell that show the current directory.
```js
// Simple Object that has toString method.
2015-01-26 17:11:25 +01:00
readlineSync.setPrompt({
toString: function() {
return '[' + require('path').basename(process.cwd()) + ']# '; // Get and show current directory.
}
});
2015-01-26 17:11:25 +01:00
```
2013-08-29 19:26:22 +02:00
2015-01-26 21:01:05 +01:00
### setPrint
2014-07-11 23:25:59 +02:00
```js
readlineSync.setPrint([callback])
2014-07-11 23:25:59 +02:00
```
The specified `callback` Function is called when any outputs are done by [Input Methods](#input-methods). The `callback` is given two arguments, `display` as the output text, and `encoding` (see [setEncoding](#setencoding) method).
2014-07-11 23:25:59 +02:00
2015-03-20 12:34:18 +01:00
For example:
2014-07-11 23:25:59 +02:00
* This is used to pass the plain texts to the Logger, when the texts are colored.
2015-03-20 12:34:18 +01:00
![sample](cl_01.png)
2014-07-11 23:25:59 +02:00
```js
2014-07-13 13:45:56 +02:00
var readlineSync = require('readline-sync'),
2015-03-20 12:34:18 +01:00
chalk = require('chalk'),
user, pw, command;
2014-07-11 23:25:59 +02:00
readlineSync.setPrint(function(display, encoding) {
2015-03-20 12:34:18 +01:00
logger.log(chalk.stripColor(display)); // Remove control characters.
2014-07-11 23:25:59 +02:00
});
2015-03-20 12:34:18 +01:00
console.log(chalk.black.bold.bgYellow(' Your Account '));
user = readlineSync.question(chalk.gray.underline(' USER NAME ') + ' :');
pw = readlineSync.question(chalk.gray.underline(' PASSWORD ') + ' :', {noEchoBack: true});
2014-07-11 23:25:59 +02:00
// Authorization ...
2015-03-20 12:34:18 +01:00
console.log(chalk.green('Welcome, ' + user + '!'));
2014-07-11 23:25:59 +02:00
2015-03-20 12:34:18 +01:00
readlineSync.setPrompt(chalk.red.bold('> '));
command = readlineSync.prompt();
2014-07-11 23:25:59 +02:00
```
* Like `your-script >foo.log`, when the output 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.
2015-03-20 12:34:18 +01:00
```js
var readlineSync = require('readline-sync');
readlineSync.setPrint(function(display, encoding) {
console.log(display); // Output to STDOUT (foo.log)
});
```
### setMask
```js
currentMask = readlineSync.setMask([newMask])
```
Set the mask character that is shown instead of the secret text (e.g. password) when `noEchoBack` option is `true` (see [noEchoBack](#noechoback) option). The default is `'*'`. 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 is redirected on Windows XP), `'*'` or `''` might be used always.
2015-03-20 12:34:18 +01:00
For example:
```js
var readlineSync = require('readline-sync'),
chalk = require('chalk'),
secret;
readlineSync.setMask(chalk.magenta('\u2665'));
secret = readlineSync.question('Please whisper sweet words :', {noEchoBack: true});
```
![sample](cl_02.png)
2015-02-22 15:45:24 +01:00
### setBufferSize
```js
currentBufferSize = readlineSync.setBufferSize([newBufferSize])
```
When readlineSync reads from a console directly (without external program), a size `newBufferSize` buffer is used. Even if the user's response exceeds it, it's usually no problem, because the buffer is used repeatedly. But, some platforms's (e.g. Windows) console might not accept user's response that exceeds it. And set an enough size. The default is `1024`.
2015-03-20 12:34:18 +01:00
### setEncoding
```js
currentEncoding = readlineSync.setEncoding([newEncoding])
```
Set the encoding method of input (user's response) and output by [Input Methods](#input-methods). The default is `'utf8'`.
2015-02-22 15:45:24 +01:00
2015-01-26 21:21:47 +01:00
## Options
An `options` Object can be specified to [Input Methods](#input-methods). This Object can have following properties.
2015-01-26 21:21:47 +01:00
### noEchoBack
Type: Boolean
Default: `false`
If `true` is specified, the secret text (e.g. password) which is typed by user on screen is hidden by the mask characters (see [setMask](#setmask) method).
2015-03-20 12:34:18 +01:00
2015-01-26 21:21:47 +01:00
For example:
```js
password = readlineSync.question('PASSWORD :', {noEchoBack: true});
console.log('Login ...');
```
The typed text is not shown on screen.
```console
2015-03-20 12:34:18 +01:00
PASSWORD :********
2015-01-26 21:21:47 +01:00
Login ...
```
### limit
Limit the user's input.
#### For keyIn method
Type: string or Array
Default: `''`
The method doesn't return until the specified key is pressed.
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']]`.
For example:
```js
if (readlineSync.keyIn('Are you sure? :', {limit: 'yn'}) === 'y') { // Accept 'y' or 'n'
execSomething();
} else {
process.exit();
}
```
### caseSensitive
Type: Boolean
Default: `false`
By default, the matching is case-insensitive when `limit` option (see [limit](#limit) option) is specified (i.e. `a` equals `A`). If `true` is specified, the matching is case-sensitive (i.e. `a` is different from `A`).
2015-01-26 21:21:47 +01:00
### noTrim
Type: Boolean
Default: `false`
By default, the leading and trailing white spaces are removed from the typed text that is returned by [Input Methods](#input-methods) except `keyIn` method. If `true` is specified, those are not removed.
2015-01-26 21:21:47 +01:00
2014-08-21 19:44:58 +02:00
## With Task Runner
2014-12-04 11:28:21 +01:00
The easy way to control the flow of task runner by the user's response:
* [Grunt](http://gruntjs.com/) plugin: [grunt-confirm](https://github.com/anseki/grunt-confirm)
* [gulp](http://gulpjs.com/) plugin: [gulp-confirm](https://github.com/anseki/gulp-confirm)
2014-08-21 19:44:58 +02:00
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 user.
Example: by using [grunt-task-helper](https://github.com/anseki/grunt-task-helper)
2014-08-21 19:44:58 +02:00
```shell
$ grunt
Running "fileCopy" task
Files already exist:
file-a.png
file-b.js
Overwrite? (y/n) :y
file-a.png copied.
file-b.js copied.
Done.
```
`Gruntfile.js`
```js
grunt.initConfig({
taskHelper: {
fileCopy: {
options: {
handlerByTask: function() {
// Abort the task if user don't want.
return readlineSync.question('Overwrite? (y/n) :')
.toLowerCase() === 'y';
// Or process.exit()
},
filesArray: []
},
...
}
},
copy: {
fileCopy: {
files: '<%= taskHelper.fileCopy.options.filesArray %>'
}
}
});
```
2014-07-14 06:28:39 +02:00
## Note
### Platforms
The TTY interfaces are different by platforms. If the platform doesn't support interactively reading from TTY, an error is thrown.
2013-12-18 03:51:32 +01:00
```js
try {
answer = readlineSync.question('What is your favorite food? :');
} catch (e) {
console.error(e);
process.exit(1);
}
```
2013-12-17 18:18:39 +01:00
### Reading by External Program
readlineSync tries to read from a console by using the external program if it is needed (e.g. when the input 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 synchronous running.
As everyone knows, "piping via files" is no good. It blocks the event loop and a process. It may make your script be slow.
Why did I choose it? :
+ The good modules (native addon) for synchronous execution exist. But node-gyp can't compile those in some platforms or Node versions.
2014-08-21 09:45:17 +02:00
+ I think that the security is important more than the speed. Some modules have problem about security. (Those don't protect data.) I think that the speed is not needed usually, because readlineSync is used while user types keys.