如何中止 readline 界面问题?

问题描述

TL;DR
一旦您致电 rl.question(query[,options],callback),它似乎无法取消该问题,只要它正在等待答复。
有没有办法彻底中止 readline 界面问题?

我在使用原生 Node.js Readline 模块时遇到了问题:

我想提供一个简单的暂停或中止功能来干预子程序(如果它花费太长时间或需要在检查时暂停)。我通过在 stdio 上提出一个可以与正在运行的子程序并行回答的问题来实现这一点。如果给出答案,则开始干预。

一切正常。但是,如果子程序完成并且在那段时间内没有给出答案,则不再需要该问题,因此我正在寻找一种干净的方法来“中止”所提出的问题。

一旦您调用 rl.question(query[,callback),它似乎无法取消问题,只要它等待回答。

我创建了这个测试代码来重现问题:

// setting up the CLI
const rl = require('readline').createInterface({
  input: process.stdin,output: process.stdout
});

// ...somewhere later:

// mockup of subroutine starting 
console.log('Start task...');

// ask question to intervene
rl.question('(p)ause/(a)bort: ',answer => {
  console.log(`You entered ${answer}`);
  // ...handle intervene. 
});

// mockup of subroutine ending
setTimeout(()=>{
  console.log('... task has ended. Question can be canelled.');
  // ...cancel the question
},5000);

我想到的临时解决方案是关闭界面,清除线路并打开一个新界面:

let rl = // ...
//...

// mockup of subroutine ending
setTimeout(() => {
  // ... cancel the question
  rl.close();
  process.stdout.clearLine();
  process.stdout.cursorTo(0);
  rl = require('readline').createInterface({
    input: process.stdin,output: process.stdout
  });
  console.log('... task has ended (and question was closed in a very dirty way).');
},5000);

它有效...但该解决方案违反了多种编码约定(关注点分离、模块化...)。
原来的readline界面是在程序的一个非常不同的位置初始化的,就这样随意关闭和重新打开它让我感到非常不愉快。 (想象一下,代码的另一部分仍然保留旧实例、.createInterface() 的原始选项得到更新等)

有没有办法彻底中止 readline 界面问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)