Reprint readline question after user input

32 Views Asked by At

I'm trying to use the user input on a readline question, to display it in front of the question after the user hits enter.

Currently i have a promisified question like this:

export const promisifyQuestion = question => {
    return new Promise(resolve =>
        rl.question(chalk.cyan.bold(`${question}\n`), res => {
            resolve(res);
        }),
    );
};

And the i tried to erase the question and user input and then print the question again but with the user input in front, like so:

export const promisifyQuestion = question => {
    return new Promise(resolve =>
        rl.question(chalk.cyan.bold(`${question}\n`), res => {
            process.stdout.write("\u001B[2k\u001B[2A\u001B[G");
            process.stdout.write(`${chalk.cyan.bold(question)} ${chalk.yellow(res)}`);
            resolve(res);
        }),
    );
};

The first stdout.write removes the last 2 line and then the second stdout.write, writes the question again but with the answer in front.

The problem is that the second stdout.write does nothing, but if i use console.log it works. But i dont want to use console.log here.

As a second question, is there a better way to remove the last 2 lines from the terminal instead of using process.stdout.write("\u001B[2k\u001B[2A\u001B[G")?

Reproducible example:

const { createInterface } = require("readline")

const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
});

const promisifyQuestion = question => {
    return new Promise(resolve =>
        rl.question(`${question}\n`, res => {
            process.stdout.write("\u001B[2k\u001B[2A\u001B[G");
            //console.log(`${question} ${res}`);
            process.stdout.write(`${question} ${res}`);
            resolve(res);
        }),
    );
};

rl.on("close", () => {
    process.exit(0);
});

async function test() {
  await promisifyQuestion("What is your name?");
}

test()

0

There are 0 best solutions below