This repository has been archived by the owner on Aug 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
prompt.js
67 lines (62 loc) · 1.64 KB
/
prompt.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
module.exports = prompt
var log = require("./log")
, buffer = ""
, stdio = process.binding("stdio")
function prompt (p, def, silent, cb) {
if (!cb) cb = silent, silent = false
if (!cb) cb = def, def = undefined
if (def) p += "("+(silent ? "<hidden>" : def)+") "
var r = (silent ? silentRead : read).bind(null, def, cb)
if (!process.stdout.write(p)) process.stdout.on("drain", function D () {
process.stdout.removeListener("drain", D)
r()
})
else r()
}
function read (def, cb) {
var stdin = process.openStdin()
, val = ""
stdin.resume()
stdin.setEncoding("utf8")
stdin.on("error", cb)
stdin.on("data", function D (chunk) {
val += buffer + chunk
buffer = ""
val = val.replace(/\r/g, '')
if (val.indexOf("\n") !== -1) {
if (val !== "\n") val = val.replace(/^\n+/, "")
buffer = val.substr(val.indexOf("\n"))
val = val.substr(0, val.indexOf("\n"))
stdin.pause()
stdin.removeListener("data", D)
val = val.trim() || def
cb(null, val)
}
})
}
function silentRead (def, cb) {
var stdin = process.openStdin()
, val = ""
stdio.setRawMode(true)
stdin.resume()
stdin.on("data", function D (c) {
c = "" + c
switch (c) {
case "\n": case "\r": case "\r\n": case "\u0004":
stdio.setRawMode(false)
stdin.removeListener("data", D)
val = val.trim() || def
process.stdout.write("\n")
process.stdout.flush()
stdin.pause()
return cb(null, val)
case "\u0003": case "\0":
return cb("cancelled")
break
default:
val += buffer + c
buffer = ""
break
}
})
}