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 Web Terminal with xterm.js and node-pty: Complete Guide

This tutorial demonstrates two ways to run a terminal in the browser: a quick setup using the webssh Python package, and a custom implementation using xterm.js on the frontend with Node.js, node-pty, and WebSocket for full terminal emulation including input handling and special keys.

Quick Implementation with webssh

The fastest way to get a browser terminal is using the mature webssh library (based on xterm.js). It requires only two steps:

Install Python 3.4+ (or 2.7) and ensure pip3 matches the Python version. On macOS, verify with python3 --version.

Run pip3 install webssh (or python3 -m pip install webssh). If pip errors occur, upgrade pip: sudo /usr/bin/python3 -m pip install --upgrade pip then reinstall.

Start the service with wssh. This launches a local WebSocket server; open the provided URL in a browser to access a fully functional terminal. For production, run in the background with process supervision.

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

Custom Implementation with xterm.js and node-pty

For deeper control, build a terminal using xterm.js (used by VS Code, Hyper, Theia) on the client and node-pty on the server.

1. Client Setup

Install xterm: npm install xterm. Create an HTML page that loads xterm.css and xterm.js, mounts a terminal on a <div id="terminal">, and writes an initial prompt.

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

Initially, the terminal cannot accept input. The xterm.js documentation shows you must listen for onData events and echo the input back:

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

2. Handling Special Keys

After enabling input, backspace and Enter keys misbehave due to encoding issues. The xterm.js encoding guide recommends using node-pty on the server to properly process raw input bytes into terminal escape sequences.

3. Architecture Overview

Client input → WebSocket → Server → node-pty virtual terminal → WebSocket → Client xterm.js rendering

4. Complete Client Code

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>

5. Complete Server Code (Node.js)

The server uses Express with express-ws for WebSocket support and node-pty to spawn a real pseudo-terminal (bash on Linux/macOS, PowerShell on Windows). A new pty instance is created per WebSocket connection to avoid stale state on page refresh.

#!/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 fresh pty per connection
  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: The server must spawn a new pty for each WebSocket connection; otherwise, refreshing the browser page leaves the old pty orphaned and breaks subsequent connections.

Result

With the server running ( node server.js) and the client page opened, you get a fully interactive terminal in the browser supporting all standard keys, colors, and commands.

xterm.js also provides many addons (search, fit, webgl, etc.) for further enhancement. See the https://xtermjs.org/ documentation for more real-world uses.

Terminal showing cat animation
Terminal showing cat animation
Console output example
Console output example
About this article

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

frontendNode.jsWebSocketwebsshxterm.jsnode-ptyterminal emulationbrowser terminal

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion