Node.js中如何重启输入?两次调用输入函数仅首次生效问题
Node.js readline第二次调用输入失效的解决方法
问题描述
首次执行第一个输入函数时可正常获取输入,但执行第二个函数时输入功能失效,相关代码如下:
import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'process'; const rl = readline.createInterface({input, output}) async function fffuncs (battlefield) { let input = await rl.question("Enter the first values: "); rl.close(); } async function ssfuncs(battlefield) { rl.resume(); let input = await rl.question("Enter the second values: "); rl.close(); } fffuncs(battlefield).then(r => input) ssfuncs(battlefield).then(r => input)
问题原因
- 第一次调用
rl.close()后,readline接口已被彻底关闭,会释放与stdin/stdout的关联,此时调用rl.resume()无法恢复已关闭的接口,自然无法再读取输入。 - 原代码中两个函数是并行执行的,会导致输入流混乱,进一步加剧问题。
解决方案
方案一:复用readline接口,所有输入完成后统一关闭
不在单个函数内关闭接口,而是等所有输入操作完成后再调用rl.close(),同时确保函数按顺序执行:
import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'process'; const rl = readline.createInterface({input, output}) async function fffuncs() { return await rl.question("Enter the first values: "); } async function ssfuncs() { return await rl.question("Enter the second values: "); } // 按顺序执行输入操作 async function runAll() { const firstInput = await fffuncs(); const secondInput = await ssfuncs(); rl.close(); // 所有输入完成后关闭接口 console.log(`第一个输入:${firstInput},第二个输入:${secondInput}`); } runAll();
方案二:每次输入前重新创建readline接口
如果需要每次输入后关闭接口,可以在每个函数内部重新创建readline实例,避免复用已关闭的接口:
import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'process'; async function fffuncs() { const rl = readline.createInterface({input, output}); const inputVal = await rl.question("Enter the first values: "); rl.close(); return inputVal; } async function ssfuncs() { const rl = readline.createInterface({input, output}); const inputVal = await rl.question("Enter the second values: "); rl.close(); return inputVal; } // 按顺序执行避免输入混乱 async function runAll() { const firstInput = await fffuncs(); const secondInput = await ssfuncs(); console.log(`第一个输入:${firstInput},第二个输入:${secondInput}`); } runAll();
内容的提问来源于stack exchange,提问作者Warface2009
相关产品推荐
相关产品推荐

