]> git.proxmox.com Git - mirror_xterm.js.git/blob - demo/app.js
Merge remote-tracking branch 'ups/master' into 687_macos_ci
[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('node-pty');
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 ws.send(data);
64 } catch (ex) {
65 // The WebSocket is not open, ignore
66 }
67 });
68 ws.on('message', function(msg) {
69 term.write(msg);
70 });
71 ws.on('close', function () {
72 term.kill();
73 console.log('Closed terminal ' + term.pid);
74 // Clean things up
75 delete terminals[term.pid];
76 delete logs[term.pid];
77 });
78 });
79
80 var port = process.env.PORT || 3000,
81 host = os.platform() === 'win32' ? '127.0.0.1' : '0.0.0.0';
82
83 console.log('App listening to http://' + host + ':' + port);
84 app.listen(port, host);