Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Build a Browser Terminal with xterm.js: From Quick Setup to Custom Implementation

This tutorial demonstrates how to create a web-based terminal using xterm.js and WebSocket, covering both a quick webssh setup and a custom implementation with Node.js backend, while solving input handling and encoding issues with node-pty.

Quick Implementation with webssh

The article begins by showing the fastest way to get a web terminal running using the webssh package, which is built on xterm.js. Only two steps are required:

Install webssh: pip install webssh (requires Python 2.7/3.4+, but the author notes using python3 -m pip install webssh or pip3 install webssh to avoid version mismatch errors).

Run the service: execute wssh in the terminal, then open the provided local URL in a browser.

For production deployment, the author notes that wssh occupies the foreground process and recommends running it in the background with process supervision.

Custom Implementation with xterm.js

For developers who want to extend functionality, the article walks through building a custom terminal using xterm.js (used by VS Code, Hyper, Theia). The process reveals several issues and their solutions:

1. Basic Setup

Install xterm: npm install xterm. Create an HTML page that loads xterm.css and xterm.js, creates a <div id="terminal"></div>, and initializes the terminal:

var term = new Terminal();
term.open(document.getElementById('terminal'));
term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');

2. Input Not Working

After the basic setup, the terminal displays output but cannot accept input. The fix is to listen for user input via term.onData and echo it back:

term.onData((value) => {
  term.write(value)
});

3. Backspace and Enter Key Issues

Even with input echoing, backspace does not delete characters and Enter moves the cursor to the first column. The author traces this to an encoding problem: xterm.js sends raw key codes that the browser cannot interpret correctly. The solution is to use node-pty on the server side to spawn a real pseudo-terminal that handles escape sequences properly.

Architecture Overview

The core logic is: client input → WebSocket → backend pseudo-terminal (node-pty) → WebSocket → client display.

Complete Client-Side Implementation

The final client uses xterm-addon-attach to connect the terminal to a WebSocket:

<!doctype html>
<html>
<head>
  <link rel='stylesheet' href='node_modules/xterm/css/xterm.css' />
  <script src='node_modules/xterm/lib/xterm.js'></script>
  <script src='https://www.unpkg.com/[email protected]/dayjs.min.js'></script>
  <script src='https://www.unpkg.com/[email protected]/lib/xterm-addon-attach.js'></script>
</head>
<body>
  <div id='terminal'></div>
  <script>
    var term = new Terminal();
    term.open(document.getElementById('terminal'));
    term.focus();
    const socketURL = 'ws://127.0.0.1:3030/socket';
    const ws = new WebSocket(socketURL);
    const attachAddon = new AttachAddon.AttachAddon(ws);
    term.loadAddon(attachAddon);
  </script>
</body>
</html>

Complete Server-Side Implementation (Node.js)

The server uses Express with express-ws for WebSocket support and node-pty to spawn a shell (bash on Unix, powershell.exe on Windows):

#!/usr/bin/env node
var express = require('express');
var app = express();
const pty = require('node-pty');
require('express-ws')(app);
const os = require('os');
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';

app.ws('/socket', (ws, req) => {
  console.log('websocket连接成功了');
  // Create a new pty for each connection to avoid stale terminals on page refresh
  const term = pty.spawn(shell, ['--login'], {
    name: 'xterm',
    cols: 50,
    rows: 24,
    cwd: process.env.HOME,
    env: process.env
  });

  ws.on('open', (data) => {
    console.log('open data===', data);
  });

  term.on('data', function (data) {
    console.log('发送给客服端的数据===', data);
    ws.send(data);
  });

  ws.on('message', (data) => {
    console.log('接收客服端的数据===', data);
    term.write(data);
  });

  ws.on('close', function () {
    term.kill();
  });
});

app.listen(3030);

Key detail: A new pty.spawn must be created for each WebSocket connection; otherwise, refreshing the browser page causes the server-side terminal to lose its connection.

References

xterm.js official site: https://xtermjs.org/

webssh GitHub: https://github.com/huashengdun/webssh

xterm.js encoding guide: https://xtermjs.org/docs/guides/encoding/

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Frontend DevelopmentNode.jsWebSocketwebsshxterm.jsterminal emulatorweb terminalnode-pty

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion