$ show microsoft/node-pty
node-pty is a Node.js native addon that provides cross-platform pseudoterminal (PTY) fork functionality. It allows spawning processes with PTY file descriptors, enabling terminal emulators like VS Code, Hyper, and xterm.js to interact with shell processes. The architecture consists of a TypeScript abstraction layer (`Terminal` base class, `UnixTerminal`, `WindowsTerminal`) that handles platform differences and wraps platform-specific C++ native modules. On Unix (Linux/macOS), it uses `forkpty(3)` and `posix_spawn`; on Windows, it leverages the ConPTY API via named pipes and worker threads to avoid deadlocks. Key entry points are the `spawn()` and `open()` functions exported from `src/index.ts`, which delegate to the appropriate platform implementation. Data flows through a pair of sockets: an input socket for writing to the PTY and an output socket for reading, with careful handling of backpressure and async I/O on each platform. The module addresses advanced challenges such as FD leakage prevention, signal handling across processes, and non-blocking I/O with custom write streams. It is a mature, well-tested library used by major terminal applications.
The LLM identified 3 files worth highlighting for reuse:
A generic, typed event emitter that returns an IDisposable subscription. It decouples event subscription from the emitter lifecycle, allowing listeners to be easily removed. The implementation iterates over a snapshot of listeners to avoid mutation issues during dispatch. This pattern is reusable in any project needing strongly-typed events with disposable subscriptions.
Contains the `argsToCommandLine` function, which correctly escapes argv to a Windows command-line string following MSDN conventions. It handles backslashes, quotes, spaces, and empty strings, implementing the complex escaping required by CommandLineToArgvW. This function is entirely self-contained and can be extracted for any Node.js project needing proper Windows command-line construction.
The `CustomWriteStream` class inside `unixTerminal.ts` is a reusable write stream that directly writes to a file descriptor, managing backpressure via an asynchronous queue and handling EAGAIN errors. It avoids the event-loop blocking issues inherent in Node.js's standard Socket write path. This pattern demonstrates deep Unix I/O knowledge and can be extracted for any low-level Node.js I/O task requiring fine-grained control.