How to use Readline.clearLine() in Node.js

The Readline.clearLine() method is contained in the ReadLine module, which provides an internal API for reading and writing data to and from the standard input.output streams.

Readline.clearLine() clears the current line on the TTY stream in the direction specified by the user.

Prototype

readline.clearLine(stream, dir[, callback])

Parameters

  • stream<stream.Writeable>: The writeable stream.

  • dir<number>: dir determines the direction relative to the cursor that will be cleared.

    1. -1: Clears line to the left of the cursor.
    2. 1: Clears line to the right of the cursor.
    3. 0: Clears the whole line.
  • callback<function>: The function that is invoked at the end of the operation.

Return value

Readline.clearLine() returns a boolean; it returns false if the stream expects the calling code to wait for the drain event to be emitted. Otherwise, Readline.clearLine() returns true.

Code

As an example, let’s write two lines on STDOUT and remove the second line.

To use the Readline module, we need to create an interface for reading and writing data to and from the stream.

An interface is an abstraction that helps us interact with the stream. Each instance of an interface is associated with a single Writeable and a single Readable stream.

We can create an instance of the interface using the readline.createInterface(), as shown below.

var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

Next, we move the cursor to the top left corner of the screen and clear the STDOUT, after which we will write two lines to STDOUT using the following lines of code.

The readline.cursorTo() method moves the cursor to the desired location, and readline.clearScreenDown() clears everything below the cursor on the stream.

The rl.write() function then writes the data onto the stream.

var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout);
rl.write("The next line will be removed\n")
rl.write("This line will be removed\n")
rl.write("The above line was removed\n")

Output

Now, we can use the readline.clearLine() function to clear the second line, as follows.

const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout);
rl.write("The next line will be removed\n")
rl.write("This line will be removed\n")
rl.write("The above line was removed\n")
readline.cursorTo(process.stdout, 0, 1);
readline.clearLine(process.stdout, 0);
rl.close();

Output

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved