You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In accordance with issue #1977, I have updated the Article **how-to-prompt-for-command-line-input** with the following changes:
1. Exchanged **direct stdin usage** with **readline module**
2. Added example of `readline` module.
3. Some other miscellaneous updates and refactors.
Copy file name to clipboardExpand all lines: locale/en/knowledge/command-line/how-to-prompt-for-command-line-input.md
+84-69Lines changed: 84 additions & 69 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -11,81 +11,96 @@ layout: knowledge-post.hbs
11
11
12
12
So you've got a little CLI tool, but you want to be able to prompt a user for additional data after the script has started, rather than passing it in as a command line argument or putting it in a file. To do this, you'll need to listen to STDIN ("standard input", i.e. your keyboard), which Node.js exposes for you as `process.stdin`, a readable stream.
13
13
14
-
Streams are Node's way of dealing with evented I/O - they're a big topic, and you can read more about them (here). For now, we're only going to deal with the Stream methods relevant to working with `process.stdin` so as to keep the examples easy.
15
-
16
-
The first two Readable Stream methods you'll need to know about here are `pause()` and `resume()`. Not every program needs to care whether or not you're pressing keys at a given moment, so `process.stdin` is paused by default.
14
+
Streams are Node's way of dealing with evented I/O - it's a big topic, and you can read more about them [here](https://nodejs.org/api/stream.html). For now, we're going to use node's `readline` module which is a wrapper around Standard I/O, suitable for taking user input from command line(terminal).
17
15
18
16
Here's a simple example. Try the following in a new file:
console.log('Now that process.stdin is paused, there is nothing more to do.');
33
-
process.exit();
34
-
}
35
-
36
-
37
-
If all of this sounds complicated, or if you want a higher-level interface to this sort of thing, don't worry - as usual, the Node.js community has come to the rescue. One particularly friendly module to use for this is Prompt, maintained by Nodejitsu. It's available on `npm`:
38
-
39
-
npm install prompt
18
+
```js
19
+
constreadline=require("readline");
20
+
constrl=readline.createInterface({
21
+
input:process.stdin,
22
+
output:process.stdout
23
+
});
24
+
25
+
rl.question("What is your name ? ", function(name) {
26
+
rl.question("Which country do you belong ? ", function(country) {
27
+
console.log(`${name}, is a citizen of ${country}`);
28
+
rl.close();
29
+
});
30
+
});
31
+
32
+
rl.on("close", function() {
33
+
console.log("\nBYE BYE !!!");
34
+
process.exit(0);
35
+
});
36
+
```
37
+
38
+
In the above code `readline.createInterface()` is used for creating an instance of `readline` by configuring the readable and the writable streams. The `input` key takes a readable stream like `process.stdin` or `fs.createReadStream('file.txt')` and the `output` key takes a writable stream like `process.stdout` or `process.stderr`.
39
+
40
+
The `rl.question()` method displays the query by writing it to the `output`, waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument.
41
+
42
+
NODE PRO TIP: Do remember to use `rl.close()` to close the transmitting otherwise the process will be left in the `idle` state.
43
+
44
+
The last part of the code uses `rl.on()` method to add an event listener to the `close` event which simply `console.log` to the output stream and exits the process. This part is completely optional and can be removed at will. For more in-depth details and usage refer to the docs [here](https://nodejs.org/api/readline.html).
45
+
46
+
If all of this sounds complicated, or if you want a higher-level interface to this sort of thing, don't worry - as usual, the Node.js community has come to the rescue. One particularly friendly module to use for this is `prompt`, available on `npm`:
47
+
48
+
```bash
49
+
npm install prompt
50
+
```
40
51
41
52
Prompt is built to be easy - if your eyes started to glaze over as soon as you saw `Readable Stream`, then this is the section for you. Compare the following to the example above:
42
53
43
-
var prompt = require('prompt');
44
-
45
-
prompt.start();
46
-
47
-
prompt.get(['username', 'email'], function (err, result) {
48
-
if (err) { return onErr(err); }
49
-
console.log('Command-line input received:');
50
-
console.log(' Username: ' + result.username);
51
-
console.log(' Email: ' + result.email);
52
-
});
53
-
54
-
function onErr(err) {
55
-
console.log(err);
56
-
return 1;
57
-
}
58
-
59
-
NODE PRO TIP: This short script also demonstrates proper error handling in node - errors are a callback's first argument, and `return` is used with the error handler so that the rest of the function doesn't execute when errors happen. For more information, look (here).
54
+
```js
55
+
constprompt=require('prompt');
56
+
57
+
prompt.start();
58
+
59
+
prompt.get(['username', 'email'], function (err, result) {
60
+
if (err) { returnonErr(err); }
61
+
console.log('Command-line input received:');
62
+
console.log(' Username: '+result.username);
63
+
console.log(' Email: '+result.email);
64
+
});
65
+
66
+
functiononErr(err) {
67
+
console.log(err);
68
+
return1;
69
+
}
70
+
```
71
+
72
+
NODE PRO TIP: This short script also demonstrates proper error handling in node - errors are a callback's first argument, and `return` is used with the error handler so that the rest of the function doesn't execute when errors happen.
60
73
61
74
Prompt also makes it trivial to handle a certain set of recurring properties that one might want to attach.
62
75
63
-
var prompt = require('prompt');
64
-
65
-
var properties = [
66
-
{
67
-
name: 'username',
68
-
validator: /^[a-zA-Z\s\-]+$/,
69
-
warning: 'Username must be only letters, spaces, or dashes'
70
-
},
71
-
{
72
-
name: 'password',
73
-
hidden: true
74
-
}
75
-
];
76
-
77
-
prompt.start();
78
-
79
-
prompt.get(properties, function (err, result) {
80
-
if (err) { return onErr(err); }
81
-
console.log('Command-line input received:');
82
-
console.log(' Username: ' + result.username);
83
-
console.log(' Password: ' + result.password);
84
-
});
85
-
86
-
function onErr(err) {
87
-
console.log(err);
88
-
return 1;
89
-
}
90
-
91
-
For more information on Prompt, please see [the project's GitHub page](http://github.com/nodejitsu/node-prompt).
76
+
```js
77
+
constprompt=require('prompt');
78
+
79
+
constproperties= [
80
+
{
81
+
name:'username',
82
+
validator:/^[a-zA-Z\s\-]+$/,
83
+
warning:'Username must be only letters, spaces, or dashes'
84
+
},
85
+
{
86
+
name:'password',
87
+
hidden:true
88
+
}
89
+
];
90
+
91
+
prompt.start();
92
+
93
+
prompt.get(properties, function (err, result) {
94
+
if (err) { returnonErr(err); }
95
+
console.log('Command-line input received:');
96
+
console.log(' Username: '+result.username);
97
+
console.log(' Password: '+result.password);
98
+
});
99
+
100
+
functiononErr(err) {
101
+
console.log(err);
102
+
return1;
103
+
}
104
+
```
105
+
106
+
For more information on Prompt, please see [the project's GitHub page](https://github.com/flatiron/prompt).
0 commit comments