nodejs
  1. nodejs-tty-terminal

Node.js TTY (Terminal)

In Node.js, TTY stands for TeleTYpewriter and it is a built-in module that provides the ability to interact with the console/terminal. The TTY module provides a way to read input from the terminal, write output to the terminal, and control the terminal. In this tutorial, we'll discuss how to use the TTY module in Node.js.

Syntax

Here is the syntax for using the TTY module in Node.js:

const tty = require('tty');

To create a new TTY object, use the following syntax:

const ttyObject = new tty.ReadStream(fd, options);
const ttyObject = new tty.WriteStream(fd, options);

Example

Here's an example that demonstrates how to use the TTY module in Node.js:

const tty = require('tty');

const stdin = process.stdin;
const stdout = process.stdout;

stdin.setRawMode(true); // Allows reading of input one character at a time
stdin.resume(); // Resumes standard input stream

stdout.write('Hello, terminal! \n');

// Handles input from the terminal
stdin.on('data', (key) => {
  if (key === '\u0003') {
    process.exit(); // Handles ctrl-c exit
  }

  stdout.write(`You pressed ${key.toString()} \n`);
});

Output

When you run the above code in a terminal, you will see the following output:

Hello, terminal!

When you press any key on the keyboard, its value will be printed to the console, until you press ctrl-c to exit.

Explanation

In the example above, we first require the tty module. We then create a stdin and stdout stream object that are associated with the standard input and standard output of the terminal.

Next, we enable reading of input one character at a time using setRawMode(). We then resume the standard input stream using resume(), which allows us to start reading input from the terminal.

We then write a message to the terminal using stdout.write(). Finally, we set up an event listener that listens for data from the terminal and prints it to the console using stdout.write().

Use

The TTY module is useful for building command-line applications that interact with the terminal. You can use the TTY module to read input from the terminal, display output to the terminal, and control the terminal. The TTY module is commonly used in command-line tools, terminal user interfaces, and screen-sharing applications.

Important Points

  • The TTY module uses standard input and standard output streams to communicate with the terminal.
  • The setRawMode() function allows you to read input one character at a time.
  • You can use the stdout.cursorTo() method to move the cursor to a specific position on the screen.

Summary

In this tutorial, we discussed how to use the TTY module in Node.js. We covered the syntax, example, output, explanation, use, and important points of the TTY module. With this knowledge, you can now use the TTY module in your Node.js applications to build powerful command-line tools and terminal user interfaces.

Published on: