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