javascript - How to read only a single line from command line in Node.js, similar to Python's `input` or C++'s `std::getline`?
问题描述
In Node, there does not seem to be a straight-forward way to easily get a single line from the commandline.
Solutions I have found so far:
readline
module'son('line', callback)
[*]readline
'squestion(q, callback)
[*]process.stdin.pipe(require('split')()).on('data', callback)
[*]fs.readFileSync(0).toString
[*]
But all of the above are not nearly as straight forward as python's input
or C++'s std::getline
. (Also, I could not get option (4) to work on Windows.)
The readline
approach is probably the best, but the fact that it requires the use of callbacks
is frustrating.
解决方案
Wrapping the dedicated readline
module's function(s) in promises is probably still the best approach. Here we emulate Python's input
and C++'s getline
functionality.
NOTE that node event's don't only have an on
function, but also a once
function.
// 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();
推荐阅读
- excel - 为什么在 VBA 中过滤 SumProduct 时出现类型不匹配错误?
- django - django 不改变登录页面
- microsoft-graph-api - 使用 Graph API 如何编写 Sharepoint“个人或组”字段?
- shell - 如何在 shell 脚本中将 yubikey pin 传递给 openssl 命令
- css - 无效的属性名称:flex-basis:1 0 max-content
- android - 如何传递类似活动的参数
- nightwatch.js - NightwatchJS 无法从元素列表中找到第二个元素
- php - 带有 array_walk_recursive 的 PHP SimpleXMLElement 正在反转键和值
- json - 如何使用地图
在 Flutter 中输入 json - dax - DAX - IsSubTotal - 似乎工作不正常?