-
Notifications
You must be signed in to change notification settings - Fork 31
/
stdio.js
64 lines (53 loc) · 1.65 KB
/
stdio.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
// This example reads commands from stdin and sends them on enter key press.
// You need to run `npm install keypress` for this example to work.
var Rcon = require('../node-rcon');
var keypress = require('keypress');
var conn = new Rcon('localhost', 1234, 'password');
var authenticated = false;
var queuedCommands = [];
conn.on('auth', function() {
console.log("Authenticated");
authenticated = true;
// You must wait until this event is fired before sending any commands,
// otherwise those commands will fail.
//
// This example buffers any commands sent before auth finishes, and sends
// them all once the connection is available.
for (var i = 0; i < queuedCommands.length; i++) {
conn.send(queuedCommands[i]);
}
queuedCommands = [];
}).on('response', function(str) {
console.log("Response: " + str);
}).on('error', function(err) {
console.log("Error: " + err);
}).on('end', function() {
console.log("Connection closed");
process.exit();
});
conn.connect();
keypress(process.stdin);
process.stdin.setRawMode(true);
process.stdin.resume();
var buffer = "";
process.stdin.on('keypress', function(chunk, key) {
if (key && key.ctrl && (key.name == 'c' || key.name == 'd')) {
conn.disconnect();
return;
}
process.stdout.write(chunk);
if (key && (key.name == 'enter' || key.name == 'return')) {
if (authenticated) {
conn.send(buffer);
} else {
queuedCommands.push(buffer);
}
buffer = "";
process.stdout.write("\n");
} else if (key && key.name == 'backspace') {
buffer = buffer.slice(0, -1);
process.stdout.write("\033[K"); // Clear to end of line
} else {
buffer += chunk;
}
});