Skip to content

Commit dc47fa1

Browse files
Yash-HandaMaledong
authored andcommitted
Update how-to-prompt-for-command-line-input (#2051)
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.
1 parent 8d435fb commit dc47fa1

1 file changed

Lines changed: 84 additions & 69 deletions

File tree

locale/en/knowledge/command-line/how-to-prompt-for-command-line-input.md

Lines changed: 84 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -11,81 +11,96 @@ layout: knowledge-post.hbs
1111

1212
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.
1313

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).
1715

1816
Here's a simple example. Try the following in a new file:
1917

20-
process.stdin.resume();
21-
process.stdin.setEncoding('utf8');
22-
var util = require('util');
23-
24-
process.stdin.on('data', function (text) {
25-
console.log('received data:', util.inspect(text));
26-
if (text === 'quit\n') {
27-
done();
28-
}
29-
});
30-
31-
function done() {
32-
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+
const readline = require("readline");
20+
const rl = 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+
```
4051

4152
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:
4253

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+
const prompt = require('prompt');
56+
57+
prompt.start();
58+
59+
prompt.get(['username', 'email'], function (err, result) {
60+
if (err) { return onErr(err); }
61+
console.log('Command-line input received:');
62+
console.log(' Username: ' + result.username);
63+
console.log(' Email: ' + result.email);
64+
});
65+
66+
function onErr(err) {
67+
console.log(err);
68+
return 1;
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.
6073

6174
Prompt also makes it trivial to handle a certain set of recurring properties that one might want to attach.
6275

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+
const prompt = require('prompt');
78+
79+
const properties = [
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) { return onErr(err); }
95+
console.log('Command-line input received:');
96+
console.log(' Username: ' + result.username);
97+
console.log(' Password: ' + result.password);
98+
});
99+
100+
function onErr(err) {
101+
console.log(err);
102+
return 1;
103+
}
104+
```
105+
106+
For more information on Prompt, please see [the project's GitHub page](https://github.com/flatiron/prompt).

0 commit comments

Comments
 (0)