readline-sync/README.md

231 lines
6.9 KiB
Markdown
Raw Normal View History

2013-08-29 19:26:22 +02:00
# readlineSync
2013-08-29 12:55:23 +02:00
2013-08-29 19:26:22 +02:00
Synchronous [Readline](http://nodejs.org/api/readline.html) for interactively running.
2014-08-10 11:16:08 +02:00
The interface is used with `process.stdin` and `process.stdout` in order to accept user input.
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? :');
2015-01-26 17:11:25 +01:00
console.log('Oh, ' + userName + ' likes ' + favFood + '!');
```
```
2015-01-26 17:11:25 +01:00
May I have your name? :AnSeki
Hi AnSeki! What is your favorite food? :chocolate
Oh, AnSeki likes chocolate!
2013-08-29 12:55:23 +02:00
```
## Installation
```
npm install readline-sync
2013-08-29 12:55:23 +02:00
```
2015-01-26 17:11:25 +01:00
## 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
```
2015-01-26 21:21:47 +01:00
Displays the `query` to the user, and then returns the user's response after it has been typed.
You can specify `options`. (see [Options](#options))
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
```
2015-01-26 21:21:47 +01:00
Displays the current prompt (See `setPrompt` method) to the user, and then returns the user's response after it has been typed.
You can specify `options`. (see [Options](#options))
2015-01-26 17:11:25 +01:00
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
```
2015-01-26 17:11:25 +01:00
Sets the prompt, for example when you run `node` on the command line, you see `> `, which is node's prompt. (See `prompt` method)
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.
}
})
```
2013-08-29 19:26:22 +02:00
2015-01-26 21:01:05 +01:00
### setEncoding
2013-08-29 19:26:22 +02:00
2013-08-29 12:55:23 +02:00
```js
currentEncoding = readlineSync.setEncoding([newEncoding])
2013-08-29 12:55:23 +02:00
```
2015-01-26 17:11:25 +01:00
Set the encoding method of input (user's response) and output (`prompt` method and `question` method). Defaults to 'utf8'.
2013-08-29 12:55:23 +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 (`prompt` method and `question` method). Defaults to `undefined`.
The `callback` is given two arguments the output text and `encoding`.
2014-07-11 23:25:59 +02:00
![sample](cl_01.png)
2015-01-26 17:11:25 +01:00
For example, this is used to pass plain texts to the Logger, when texts are colored.
2014-07-11 23:25:59 +02:00
```js
2014-07-13 13:45:56 +02:00
var readlineSync = require('readline-sync'),
user, pw, command;
2014-07-11 23:25:59 +02:00
require('colors');
readlineSync.setPrint(function(display, encoding) {
2015-01-26 17:11:25 +01:00
logger.log(display.stripColors); // Remove control characters.
2014-07-11 23:25:59 +02:00
});
console.log('Your account required.'.grey);
user = readlineSync.question('USER NAME'.white.inverse + ': ');
2014-07-12 00:37:25 +02:00
pw = readlineSync.question('PASSWORD'.white.inverse + ': ', {noEchoBack: true});
2014-07-11 23:25:59 +02:00
// Authorization ...
console.log(('Welcome, ' + user + '!').green.bold);
readlineSync.setPrompt('> '.bold.red);
command = readlineSync.prompt();
2014-07-11 23:25:59 +02:00
```
2015-02-22 15:45:24 +01:00
### setBufferSize
```js
currentBufferSize = readlineSync.setBufferSize([newBufferSize])
```
2015-02-22 15:55:08 +01:00
When readlineSync reads from TTY directly (without reading by shell), 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 TTY may not accept user's response that is too long. And set an enough size. Defaults to 1024.
2015-02-22 15:45:24 +01:00
2015-01-26 21:21:47 +01:00
## Options
An `options` Object can be specified to `prompt` method and `question` method. This Object can have following properties.
### noEchoBack
Type: Boolean
Default: `false`
If `true` is specified, echo back is avoided. It is used to hide the secret text (e.g. password) which is typed by user on screen.
For example:
```js
password = readlineSync.question('PASSWORD :', {noEchoBack: true});
console.log('Login ...');
```
The typed text is not shown on screen.
2015-02-22 12:57:07 +01:00
```
2015-01-26 21:21:47 +01:00
PASSWORD :
Login ...
```
### noTrim
Type: Boolean
Default: `false`
By default, the leading and trailing white spaces are removed from typed text. If `true` is specified, those are not removed.
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 stdin interfaces are different by platforms. If the platform doesn't support interactively reading from stdin, 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 shell
readlineSync tries reading from stdin by shell if it is needed. 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-), it use "piping via files" for synchronous running.
As everyone knows, "piping via files" is no good. It blocks 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.
2013-08-29 12:55:23 +02:00
## Release History
2015-02-22 15:45:24 +01:00
* 2015-02-22 v0.6.0 Add `setBufferSize()`.
* 2015-02-12 v0.5.5 Support the Synchronous Process Execution of Node v0.12(v0.11).
2015-01-26 17:11:25 +01:00
* 2015-01-27 v0.5.0 Add `options.noTrim`.
* 2014-07-12 v0.4.0 Add `options.noEchoBack`.
* 2014-07-12 v0.3.0 Add `setPrint()`.
* 2013-08-30 v0.2.0 Rewrite exporting methods.
* 2013-08-29 v0.1.0 Initial release.