【问题标题】:Readline works only for the first timeReadline 仅适用于第一次
【发布时间】:2019-12-03 09:59:47
【问题描述】:

我正在使用 Node 的 readline,但它只在第一次工作。 第一次尝试一切正常(answer 已记录并且readline 已关闭)但另一次看起来readline 没有被关闭(answer 从未被记录并且控制台仍在等待我的输入甚至如果我已经发送了)。

我在 Node.js 中上课(使用带有 Babel 和 Nodemon 的 ES6),它的构造函数中有 readline

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();

控制台看起来像:

> Question: answer
> answer
> Question: second answer
> I can still write
> nothing happens...

【问题讨论】:

  • 只是不要在你的回调中关闭 readline 接口
  • close() 关闭整个实例?我认为它只是关闭输入侦听器。我认为你提到的问题是一个不同类型的问题。我只有一个带有滥用关闭功能的 readline 实例。您可以提供它作为答案。

标签: node.js


【解决方案1】:

不要在你的回调中调用.close()函数,因为它会关闭整个readline接口

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

正如documentation 所说:

rl.close() 方法关闭 readline.Interface 实例并放弃对输入和输出流的控制。 [来源:nodejs.org]

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2023-04-03
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多