'How to abort a readline interface question?

TL;DR
Once you call rl.question(query[, options], callback) it looks like there is no way to cancel the question as long als it's pending an answer.
Is there a way to cleanly abort a readline interface question?

I ran into a problem using the native Node.js Readline module:

I wanted to provide a simple pause-or-abort feature to intervene in a subroutine (if it takes too long or needs pausing while inspection). I achieved this by asking a question over stdio that can be answered parallel to the running subroutine. If an answer is given an intervention is started.

That works all fine. But if the subroutine finishes and no answer was given in that time, the question is no longer needed, so I'm looking for a clean way to "abort" the asked question.

Once you call rl.question(query[, options], callback) it looks like there is no way to cancel the question as long als it's pending an answer.

I created this test code to reproduce the problem:

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

The temporary solution I came up with was to close the interface, clear the line and open a new interface:

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

It works... but this solution violates multiple coding conventions (separation of concerns, modularity...).
The original readline interface was initialized at a very different location of the program and I feel very unpleasant by casually closing and reopening it just like that. (Imagine another part of the code still keeps hold of the old instance, the original options for .createInterface() getting updated, etc.)

Is there a way to cleanly abort a readline interface question?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source