rl.question(query[, options], callback)


  • query <string> 要写入 output 的语句或查询,附加在提示的前面。
  • options <Object>
    • signal <AbortSignal> 可选地允许使用 AbortController 取消 question()
  • callback <Function> 一个回调函数,当用户对 query 做出响应输入时会被调用。

rl.question() 方法通过将 query 写入 output 来显示问题,等待用户在 input 上提供输入,然后调用 callback 函数,将提供的输入作为第一个参数传递给它。

【The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, then invokes the callback function passing the provided input as the first argument.】

当被调用时,如果 input 流已被暂停,rl.question() 将会恢复该流。

【When called, rl.question() will resume the input stream if it has been paused.】

如果使用 output 设置为 nullundefined 创建了 readline.Interface,则不会写入 query

【If the readline.Interface was created with output set to null or undefined the query is not written.】

传递给 rl.question()callback 函数不遵循通常接受 Error 对象或 null 作为第一个参数的模式。callback 会被调用,并将提供的答案作为唯一参数传入。

【The callback function passed to rl.question() does not follow the typical pattern of accepting an Error object or null as the first argument. The callback is called with the provided answer as the only argument.】

如果在 rl.close() 之后调用 rl.question(),将会抛出错误。

【An error will be thrown if calling rl.question() after rl.close().】

用法示例:

【Example usage:】

rl.question('What is your favorite food? ', (answer) => {
  console.log(`Oh, so your favorite food is ${answer}`);
}); 

使用 AbortController 来取消一个问题。

【Using an AbortController to cancel a question.】

const ac = new AbortController();
const signal = ac.signal;

rl.question('What is your favorite food? ', { signal }, (answer) => {
  console.log(`Oh, so your favorite food is ${answer}`);
});

signal.addEventListener('abort', () => {
  console.log('The food question timed out');
}, { once: true });

setTimeout(() => ac.abort(), 10000);