1 回答

TA贡献1831条经验 获得超9个赞
将专用readline模块的功能包装在 promises 中可能仍然是最好的方法。这里我们模拟 Pythoninput和 C++ 的getline功能。
请注意,节点事件不仅具有on功能,而且具有once功能。
// input.js
const readline = require('readline');
const cmd = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/**
* Emulate Python's `input` function.
*/
export async function input(prompt) {
return new Promise(r => cmd.question(prompt, r));
}
/**
* Emulate C++'s `getline` function.
*/
export async function getline() {
return new Promise(r => cmd.once('line', r));
}
// main.js
async function main() {
const x = await input('What is x?');
console.log('x is', x);
console.log('What is y?');
const y = await getline();
console.log('y is', y);
}
main();
添加回答
举报