-
Notifications
You must be signed in to change notification settings - Fork 0
/
ioUtils.js
49 lines (42 loc) · 1.14 KB
/
ioUtils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict'
import readline from 'readline'
export const getInput = async(
msg /* COULDDO: , wipeout=false, hash=undefined */
) => {
// note: being inside async ensures properly going out of scope, ensuring main ends properly
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
return await new Promise((resolve) => {
rl.question(`\u001b[38;5;202m${msg}: \u001b[0m`, resolve)
// no rl.close() here!
})
}
// remember to use `await` when calling this function!
// • sleeps for ms seconds,
// • earlier if key pressed
//
// @returns '' if no key pressed, key character otherwise
export const sleepWithKeypress = async(ms) => new Promise(resolve => {
const timer = setTimeout(() => {
rl.close()
resolve('')
}, ms)
process.stdin.setRawMode(true)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
})
readline.emitKeypressEvents(process.stdin) // needed.
process.stdin.on('keypress', (char, _key) => {
clearTimeout(timer)
rl.close()
resolve(char)
})
})
export default {
getInput,
sleepWithKeypress
}