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
|
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)+") "
process.stdout.write(p)
process.stdout.flush()
return (silent) ? silentRead(def, cb) : read(def, cb)
}
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
}
})
}
|