-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (79 loc) · 2.2 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var tty = require('tty');
module.exports = function () {
var opts = {
seperator : '*',
in : process.stdin,
out : process.stdout,
cb : function () {}
};
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
switch (typeof arg) {
case 'string' :
opts.seperator = arg;
break;
case 'function' :
opts.cb = arg;
break;
case 'object' :
if (arg.writable) {
opts.out = arg;
}
if (arg.readable) {
opts.in = arg;
}
break;
}
}
var stream = {
in : opts.in,
out : opts.out
};
var sep = opts.seperator;
var cb = opts.cb;
if (stream.in === process.stdin) {
tty.setRawMode(true);
}
var line = '';
stream.in.on('data', function ondata (buf) {
function finish () {
if (stream.in === process.stdin) {
tty.setRawMode(false);
}
if (stream.in.pause) stream.in.pause();
stream.in.removeListener('data', ondata);
}
if (buf.length === 1) {
if (buf[0] === 3) {
finish();
process.exit();
}
else if (buf[0] === 4) {
finish();
cb(line);
return;
}
else if (buf[0] === 0x7f) {
if (stream.out && line.length) {
stream.out.write('\b \b');
}
line = line.slice(0,-1);
return;
}
}
for (var i = 0; i < buf.length; i++) {
var c = String.fromCharCode(buf[i]);
if (c === '\n' || c === '\r') {
finish();
if (stream.out) stream.out.write('\r\n');
cb(line);
break;
}
else {
if (stream.out) stream.out.write(sep);
line += c;
}
}
});
if (stream.in.resume) stream.in.resume();
};