rl.question(query[, options])


  • query <string> 要写入 output 的声明或查询,将其添加到提示的前面。
  • options <Object>
    • signal <AbortSignal> 可选,允许使用 AbortSignal 取消 question()
  • 返回值: <Promise> 一个在用户对 query 作出响应后完成的 Promise。

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 创建了 readlinePromises.Interfacequery 将不会被写入。

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

如果在 rl.close() 之后调用该问题,它将返回一个被拒绝的 Promise。

【If the question is called after rl.close(), it returns a rejected promise.】

用法示例:

【Example usage:】

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

使用 AbortSignal 来取消一个问题。

【Using an AbortSignal to cancel a question.】

const signal = AbortSignal.timeout(10_000);

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

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