]> git.proxmox.com Git - mirror_xterm.js.git/blob - demo/app.js
Add XON/XOFF and eparate write from processing
[mirror_xterm.js.git] / demo / app.js
1 var express = require('express');
2 var app = express();
3 var expressWs = require('express-ws')(app);
4 var os = require('os');
5 var pty = require('pty.js');
6
7 var terminals = {},
8 logs = {};
9
10 app.use('/build', express.static(__dirname + '/../build'));
11
12 app.get('/', function(req, res){
13 res.sendFile(__dirname + '/index.html');
14 });
15
16 app.get('/style.css', function(req, res){
17 res.sendFile(__dirname + '/style.css');
18 });
19
20 app.get('/main.js', function(req, res){
21 res.sendFile(__dirname + '/main.js');
22 });
23
24 app.post('/terminals', function (req, res) {
25 var cols = parseInt(req.query.cols),
26 rows = parseInt(req.query.rows),
27 term = pty.spawn(process.platform === 'win32' ? 'cmd.exe' : 'bash', [], {
28 name: 'xterm-color',
29 cols: cols || 80,
30 rows: rows || 24,
31 cwd: process.env.PWD,
32 env: process.env
33 });
34
35 console.log('Created terminal with PID: ' + term.pid);
36 terminals[term.pid] = term;
37 logs[term.pid] = '';
38 term.on('data', function(data) {
39 logs[term.pid] += data;
40 });
41 res.send(term.pid.toString());
42 res.end();
43 });
44
45 app.post('/terminals/:pid/size', function (req, res) {
46 var pid = parseInt(req.params.pid),
47 cols = parseInt(req.query.cols),
48 rows = parseInt(req.query.rows),
49 term = terminals[pid];
50
51 term.resize(cols, rows);
52 console.log('Resized terminal ' + pid + ' to ' + cols + ' cols and ' + rows + ' rows.');
53 res.end();
54 });
55
56 app.ws('/terminals/:pid', function (ws, req) {
57 var term = terminals[parseInt(req.params.pid)];
58 console.log('Connected to terminal ' + term.pid);
59 ws.send(logs[term.pid]);
60
61 term.on('data', function(data) {
62 try {
63 // XOFF - stop pty pipe
64 // XON will be triggered by emulator before processing data chunk
65 term.write('\x13');
66 ws.send(data);
67 } catch (ex) {
68 // The WebSocket is not open, ignore
69 }
70 });
71 ws.on('message', function(msg) {
72 term.write(msg);
73 });
74 ws.on('close', function () {
75 process.kill(term.pid);
76 console.log('Closed terminal ' + term.pid);
77 // Clean things up
78 delete terminals[term.pid];
79 delete logs[term.pid];
80 });
81 });
82
83 var port = process.env.PORT || 3000,
84 host = os.platform() === 'win32' ? '127.0.0.1' : '0.0.0.0';
85
86 console.log('App listening to http://' + host + ':' + port);
87 app.listen(port, host);