Remote terminal with Total.js + Node PTY + xTerm
A simple tutorial how to create a remove terminal with help of Total.js Platform and modules Node PTY + xTerm.
Remote terminal with Total.js + Node PTY + xTerm
Node.js dependencies:
Client-side dependencies:
Server-Side implementation
const Pty = require('node-pty');
exports.install = function() {
// Route to views/index
ROUTE('/');
// WebSocket route
WEBSOCKET('/', socket, ['raw']);
};
function socket() {
var self = this;
self.encodedecode = false;
self.autodestroy();
self.on('open', function(client) {
// Each client will have own terminal
client.tty = Pty.spawn('/bin/bash', [], { name: 'xterm-color', cols: 80, rows: 24, cwd: process.env.PWD, env: process.env });
client.tty.on('exit', function(code, signal) {
// What now?
client.tty = null;
client.close();
});
client.tty.on('data', function(data) {
client.send(data);
});
});
self.on('close', function(client) {
if (client.tty) {
client.tty.kill(9);
client.tty = null;
}
});
self.on('message', function(client, msg) {
client.tty && client.tty.write(msg);
});
}
Client-Side implementation
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Remote terminal</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/xterm/3.14.5/xterm.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/xterm/3.14.5/xterm.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xterm/3.14.5/addons/attach/attach.js"></script>
</head>
<body>
<div id="terminal"></div>
<script>
var term = new Terminal({ cols: 80, rows: 24 });
term.open(document.getElementById('terminal'));
var ws = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.hostname + (location.port ? (':' + location.port) : '') + '/');
ws.onopen = function() {
new attach.attach(term, ws);
};
ws.onerror = function(e) {
console.log(e);
};
</script>
</body>
</html>
Other posts from Total.js Platform