How to use the keyIn function from readline-sync

Find comprehensive JavaScript readline-sync.keyIn code examples handpicked from public code repositorys.

readline-sync.keyIn is a synchronous function that waits for user input from the keyboard and returns the pressed key.

0
1
2
3
4
5
6
7
8
9
const readLine = require('readline-sync');
// const name = readLine.question("What's your name?");
// console.log('Welcome ', name);

while (true) {
  const key = readLine.keyIn('Press a key');
  if (key === 'q') {
    process.exit(0);
  }
  if (key === 'a') {
fork icon0
star icon2
watch icon2

+ 15 other calls in file

76
77
78
79
80
81
82
83
84
85
  '[Z] <- -> [X]  FIX: [SPACE]\n');
while (true) {
  console.log('\x1B[1A\x1B[K|' +
    (new Array(value + 1)).join('-') + 'O' +
    (new Array(MAX - value + 1)).join('-') + '| ' + value);
  key = readlineSync.keyIn('',
    {hideEchoBack: true, mask: '', limit: 'zx '});
  if (key === 'z') { if (value > MIN) { value--; } }
  else if (key === 'x') { if (value < MAX) { value++; } }
  else { break; }
fork icon61
star icon1
watch icon2

+ 47 other calls in file

How does readline-sync.keyIn work?

readline-sync.keyIn is a synchronous method of the readline-sync module in Node.js that waits for user input from the terminal and returns the input as a string or a number, based on the options provided, until a specific key is pressed.

212
213
214
215
216
217
218
219
220
The `query` is handled the same as that of the [`question`](#basic_methods-question) method.

For example:

```js
menuId = readlineSync.keyIn('Hit 1...5 key: ', {limit: '$<1-5>'});
```

### <a name="basic_methods-setdefaultoptions"></a>`setDefaultOptions`
fork icon156
star icon0
watch icon1

+ 5 other calls in file

74
75
76
77
78
79
80
81
82
    }
});
console.log('Exited');


pressedKey = readlineSync.keyIn("What is your age\nA :10\nB :20\n", {
    limit: '${A-D}'
});
console.log(pressedKey)
fork icon1
star icon3
watch icon2

+ 3 other calls in file

Ai Example

1
2
3
4
const readlineSync = require("readline-sync");
const choices = ["rock", "paper", "scissors"];
const index = readlineSync.keyInSelect(choices, "What's your choice?");
console.log(`You chose ${choices[index]}`);

In this example, the keyInSelect function is used to prompt the user to select a choice from the provided array of options, and the user's choice is returned as the index of the selected option. The index is then used to retrieve the corresponding value from the array.

-4
fork icon0
star icon0
watch icon1

+ 3 other calls in file

-3
fork icon0
star icon0
watch icon1

+ 3 other calls in file