-
Notifications
You must be signed in to change notification settings - Fork 114
/
pty_bridge.js
78 lines (67 loc) · 1.69 KB
/
pty_bridge.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
/**
* Copyright 2014 Simon Edwards <simon@simonzone.com>
*/
var pty = require('pty.js');
var flexbuffer = require('./flexbuffer');
var inputbuffer = new flexbuffer.FlexBuffer();
var term = pty.spawn('bash', [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});
term.on('data', function(data) {
process.stdout.write(data);
});
term.on('exit', function() {
console.log("pty_bridge: term process exited.");
process.exit(0);
});
/**
* Processes packets.
*
* The two packets types which are supported are chars and resize commands:
* {stream: "...char data..."}
* {resize: [cols, rows]}
*/
function processPacket(data) {
if (data.resize !== undefined) {
// Resize the terminal.
term.resize(data.resize[0], data.resize[1]);
} else {
term.write(data.stream);
}
}
function processStdin(chunk) {
var payloadSize;
var jsonPacket;
var packetSize;
inputbuffer.appendBuffer(chunk);
while (inputbuffer.size() >= 4) {
payloadSize = inputbuffer.buffer.readUInt32BE(0);
packetSize = 4 + payloadSize;
if (inputbuffer.size() >= packetSize) {
jsonPacket = inputbuffer.buffer.toString('utf8', 4, packetSize);
inputbuffer.delete(0, packetSize);
processPacket(JSON.parse(jsonPacket));
} else {
break;
}
}
}
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
while (null !== chunk) {
processStdin(chunk);
chunk = process.stdin.read();
}
});
process.stdin.on('close', function() {
console.log("stdin closed. exiting");
process.exit(0);
});
process.stdin.on('error', function() {
console.log("stdin errored. exiting");
process.exit(0);
});