UNPKG

1.02 kBJavaScriptView Raw
1const rl = require('readline')
2
3const _ = module.exports = {}
4
5// Convention: "no" should be the conservative choice.
6// If you mistype the answer, we'll always take it as a "no".
7// You can control the behavior on <Enter> with `isYesDefault`.
8_.prompt = function (question, isYesDefault) {
9 if (typeof isYesDefault !== 'boolean') {
10 throw new TypeError('Provide explicit boolean isYesDefault as second argument.')
11 }
12 return new Promise(resolve => {
13 const rlInterface = rl.createInterface({
14 input: process.stdin,
15 output: process.stdout
16 })
17
18 const hint = isYesDefault === true ? '[Y/n]' : '[y/N]'
19 const message = question + ' ' + hint + '\n'
20
21 rlInterface.question(message, answer => {
22 rlInterface.close()
23
24 const useDefault = answer.trim().length === 0
25 if (useDefault) {
26 return resolve(isYesDefault)
27 }
28
29 const isYes = answer.match(/^(yes|y)$/i)
30 return resolve(isYes)
31 })
32 })
33}
34
35_.clear = function () {
36 process.stdout.write('\x1Bc')
37}