Skip to content

Instantly share code, notes, and snippets.

@capan
Created November 22, 2019 14:27
Show Gist options
  • Save capan/dc2976b975490173c156c8a91a3d7c52 to your computer and use it in GitHub Desktop.
Save capan/dc2976b975490173c156c8a91a3d7c52 to your computer and use it in GitHub Desktop.
React + Node.js Terminal emulation
import React from 'react';
import { Terminal } from 'xterm';
import PageBase from './pages/PageBase';
import openSocket from 'socket.io-client';
import { FitAddon } from 'xterm-addon-fit';
class ReactTerminal extends PageBase {
constructor(props) {
super(props);
this.state = {};
this.serverUrl = 'localhost'
}
componentDidMount() {
const term = new Terminal();
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.open(document.getElementById('terminal'));
let socket = openSocket('http://' + this.serverUrl + ':8080');
socket.on('output', data => {
if (socket.connected) {
term.write(data);
}
});
socket.on('connect', s => {
term.write('\x1b[2K\r');
});
term.onData(data => {
if (socket.connected) {
if (data.charCodeAt(0) < 32 && data.charCodeAt(0) != 27 && data.charCodeAt(0) != 13) {
console.log(data.charCodeAt(0));
}
else {
socket.emit("input", data);
};
} else {
term.write('\x1b[2K\r');
term.write('\x1B[1;3;31mConnection Error!\x1B[0m');
}
});
}
render() {
return (
<div id="terminal"></div>
)
}
}
export default ReactTerminal
const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const pty = require('node-pty');
const os = require('os');
let app = express();
app.use("/", express.static("./"));
let server = http.createServer(app).listen(8080);
let io = require('socket.io')(server);
// cross platform work
let shell = os.platform() === "win32" ? 'powershell.exe' : 'bash';
io.on('connection', function (socket) {
let term = pty.spawn(shell, [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env,
});
term.on('data', function (data) {
term.write(data)
socket.emit('output', data);
});
socket.on('input', function (data) {
let authenticated = false
term.write(data);
});
socket.on('disconnect', function () {
term.destroy();
console.log("Terminal destroyed");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment