Use pty.spawn() to fork a process with a pseudoterminal file descriptor. This returns a terminal object that supports reading data, writing data, and resizing. This is the primary way to create a terminal emulator or run programs that require a TTY environment.
Common options for the spawn configuration include:
name: The terminal type (e.g., 'xterm-color').cols: Number of columns.rows: Number of rows.cwd: Current working directory.env: Environment variables.handleFlowControl: Boolean to enable automatic XON/XOFF flow control.
import * as os from 'node:os';
import * as pty from 'node-pty';
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
const ptyProcess = pty.spawn(shell, [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});
ptyProcess.onData((data) => {
process.stdout.write(data);
});
ptyProcess.write('ls\r');
ptyProcess.resize(100, 40);
ptyProcess.write('ls\r');