Node.js `tty` Module: Interacting with the Terminal and Console

Learn how to use Node.js's `tty` module for terminal and console interaction. This tutorial explains accessing the TTY interface, working with input and output streams (`tty.ReadStream`, `tty.WriteStream`), and building command-line applications or other programs requiring direct terminal control.



Working with Node.js's TTY (Teletypewriter) Module

Node.js's `tty` module provides access to the teletypewriter (TTY) interface, allowing interaction with the terminal or console. This is essential for creating command-line applications or other programs requiring direct terminal input and output.

Accessing the `tty` Module

To use the `tty` module, you need to require it:


const tty = require('tty');

If Node.js is running in a TTY environment (connected to a terminal), `process.stdin` will be a `tty.ReadStream` object, and `process.stdout` will be a `tty.WriteStream` object. You can check this using:


node -p -e "console.log(process.stdout.isTTY)"

`tty.ReadStream`

Represents the readable side of a TTY. Typically, `process.stdin` is an instance of `tty.ReadStream` when running in a TTY environment.

Key Properties and Methods

  • isRaw (boolean): Indicates if the stream is in raw mode (default is `false`).
  • setRawMode(mode): Sets the raw mode. `true` enables raw mode; `false` disables it. The `isRaw` property is updated to reflect the new mode. Raw mode passes keystrokes directly to the application without processing special keys.

`tty.WriteStream`

Represents the writable side of a TTY. `process.stdout` is usually an instance of `tty.WriteStream`.

Key Properties and Events

  • 'resize' event: Emitted when the terminal window is resized. The `columns` and `rows` properties are updated.
  • columns (number): The number of columns in the terminal.
  • rows (number): The number of rows in the terminal.

Example: Handling Keypresses and Window Resizes


const tty = require('tty');

process.stdin.setRawMode(true);
process.stdin.resume();
console.log('Press Ctrl+C to exit.');

process.stdin.on('keypress', (char, key) => {
    if (key && key.ctrl && key.name === 'c') {
        process.exit();
    }
});

process.stdout.on('resize', () => {
    console.log('Screen resized!');
    console.log(`${process.stdout.columns}x${process.stdout.rows}`);
});