2

I'm using Node's readline but it works only for the first time. At the first try everything works well (answer is logged and readline is closed) but another time it looks like the readline is not being closed (answer is never logged and console is still waiting for my input even if I've already sent it).

I've class in Node.js (using ES6 with Babel and Nodemon) which has readline in constructor.

class SomeClass
{
    constructor(readline) {
        this.readline = readline;
    }

    askPath() {
        this.readline.question('Question: ', (answer) => {
            console.log(answer);
            this.readline.close();
            this.askPath();
        });
    }
}

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

let someClass = new SomeClass(rl);
someClass.askPath();

Console looks like:

> Question: answer
> answer
> Question: second answer
> I can still write
> nothing happens...
Jax-p
  • 7,225
  • 4
  • 28
  • 58
  • just don't close readline interface in your callback – Krzysztof Krzeszewski Dec 03 '19 at 10:04
  • 1
    Does this answer your question? [How to take two consecutive input with the readline module of node.js?](https://stackoverflow.com/questions/36540996/how-to-take-two-consecutive-input-with-the-readline-module-of-node-js) – Krzysztof Krzeszewski Dec 03 '19 at 10:06
  • `close()` closes whole instance? I thought it just close input listener. I think the question which has you mentioned is a different kind of question. I've only one instance of readline with misused close function. You can provide it as an answer. – Jax-p Dec 03 '19 at 10:11

1 Answers1

3

Just don't call the .close() function, inside of your callback as it closes the entire readline interface

askPath() {
    this.readline.question('Question: ', (answer) => {
        console.log(answer);
        this.askPath();
    });
}

As the documentation says:

The rl.close() method closes the readline.Interface instance and relinquishes control over the input and output streams. [source:nodejs.org]

Jax-p
  • 7,225
  • 4
  • 28
  • 58
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30