rl.question(query[, options])
query
<string> 要写入output
的语句或查询,位于提示之前。options
<Object>signal
<AbortSignal> 可选择允许使用AbortSignal
取消question()
。
- 返回: <Promise> 使用用户响应
query
的输入履行的 promise。
rl.question()
方法通过将 query
写入 output
来显示 query
,等待在 input
上提供用户输入,然后调用 callback
函数,将提供的输入作为第一个参数传入。
当调用时,如果 rl.question()
流已暂停,则 rl.question()
将恢复 input
流。
如果 readlinePromises.Interface
是在 output
设置为 null
或 undefined
的情况下创建的,则不会写入 query
。
如果问题在 rl.close()
之后被调用,则它返回被拒绝的 promise。
用法示例:
const answer = await rl.question('What is your favorite food? ');
console.log(`Oh, so your favorite food is ${answer}`);
使用 AbortSignal
取消问题。
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}`);
query
<string> A statement or query to write tooutput
, prepended to the prompt.options
<Object>signal
<AbortSignal> Optionally allows thequestion()
to be canceled using anAbortSignal
.
- Returns: <Promise> A promise that is fulfilled with the user's
input in response to the
query
.
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.
When called, rl.question()
will resume the input
stream if it has been
paused.
If the readlinePromises.Interface
was created with output
set to null
or
undefined
the query
is not written.
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}`);
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}`);