如何从node.js中的命令行读取用户输入以进行简单计算?我一直在阅读http://nodejs.org/api/readline.html#readline_readline和http://nodejs.org/api/process.html#process_process_stdin,但我不能将我的输入用于console.log(input)
等简单的事情。我知道这些是异步函数,但我想必须有一种方法可以将输入用于以后的计算。
你有一个例子吗?像两个给定数字的总和:输入a和b并输出a + b
答案 0 :(得分:3)
这样的东西?
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function processSum(number) {
// Insert code to do whatever with sum here.
console.log('The sum is', number);
}
rl.question('Enter a number: ', function (x) {
rl.question('Enter another number: ', function (y) {
var sum = parseFloat(x) + parseFloat(y);
processSum(sum)
rl.close();
});
});
答案 1 :(得分:0)
您可以编写这样的可重用模块:
// ask.js
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.pause();
function ask(question, cb = () => void 0) {
return new Promise(resolve => {
rl.question(question, (...args) => {
rl.pause();
resolve(...args);
cb(...args);
});
});
}
module.exports = ask;
并在各处使用多种方法:
async/await
):const ask = require("./ask");
(async () => {
const a = await ask("Enter the first number: ");
const b = await ask("Enter the second number: ");
console.log("The sum is", a + b);
})();
Promise
):const ask = require("./ask");
ask("Enter the first number: ")
.then(a => {
ask("Enter the second number: ")
.then(b => {
console.log("The sum is", a + b);
});
});
callback
):const ask = require("./ask");
ask("Enter the first number: ", a => {
ask("Enter the second number: ", b => {
console.log("The sum is ", a + b);
});
});