node.js stdout clearline() and cursorTo() functions

This is the solution :

First, require readline :

var readline = require('readline');

Then, use cursorTo like this :

function writeWaitingPercent(p) {
    //readline.clearLine(process.stdout);
    readline.cursorTo(process.stdout, 0);
    process.stdout.write(`waiting ... ${p}%`);
}

I've commented clearLine, since it's useless in my case (cursorTo move back the cursor to the start)


The Readline module that is part of Node.js now provides readline.cursorTo(stream, x, y), readline.moveCursor(stream, dx, dy) and readline.clearLine(stream, dir) methods.


With TypeScript, your code should look like this:

import * as readline from 'readline'
// import readline = require('readline') also works

/* ... */

function writeWaitingPercent(p: number) {
    readline.clearLine(process.stdout, 0)
    readline.cursorTo(process.stdout, 0, null)
    let text = `waiting ... ${p}%`
    process.stdout.write(text)
}

The previous code will transpile into the following Javascript (ES6) code:

const readline = require('readline');

/* ... */

function writeWaitingPercent(p) {
    readline.clearLine(process.stdout, 0);
    readline.cursorTo(process.stdout, 0, null);
    let text = `waiting ... ${p}%`;
    process.stdout.write(text);
}

As an alternative, you can use the following code for Javascript (ES6):

const readline = require('readline');

/* ... */

function waitingPercent(p) {
    readline.clearLine(process.stdout, 0)
    readline.cursorTo(process.stdout, 0)
    let text = `waiting ... ${p}%`
    process.stdout.write(text)
}

Tags:

Node.Js