[英]How to take two consecutive input with the readline module of node.js?
我正在創建一個程序來從命令行輸入兩個數字,然后在 node.js 中顯示總和。我正在使用 readline 模塊來獲取標准輸入。 下面是我的代碼。
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const r2 = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Please enter the first number', (answer1) => {
r2.question('Please enter the second number', (answer2) => {
var result = (+answer1) + (+answer2);
console.log(`The sum of above two numbers is ${result}`);
});
rl.close();
});
這個程序只告訴我“請輸入第一個數字”,當我輸入像 5 這樣的數字時,第二個輸入也需要 5,並顯示答案 10
它根本不問第二個問題。 請檢查這個並告訴我問題是什么。 如果有任何更好的方法來獲取多個輸入,請告訴我。
我是node.js的新手用戶
不需要另一個變量,只需使用如下:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Please enter the first number : ', (answer1) => {
rl.question('Please enter the second number : ', (answer2) => {
var result = (+answer1) + (+answer2);
console.log(`The sum of above two numbers is ${result}`);
rl.close();
});
});
嵌套代碼/回調很難閱讀和維護,這是使用Promise提出多個問題的更優雅方式
節點8+
'use strict'
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const question1 = () => {
return new Promise((resolve, reject) => {
rl.question('q1 What do you think of Node.js? ', (answer) => {
console.log(`Thank you for your valuable feedback: ${answer}`)
resolve()
})
})
}
const question2 = () => {
return new Promise((resolve, reject) => {
rl.question('q2 What do you think of Node.js? ', (answer) => {
console.log(`Thank you for your valuable feedback: ${answer}`)
resolve()
})
})
}
const main = async () => {
await question1()
await question2()
rl.close()
}
main()
const readline = require("readline")
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var questions = [
"Input first number",
"Input second number",
"Input third number",
"Input fourth number",
"Input fifth number",
];
const askQuestion = (theQuestion) => {
return new Promise((resolve, reject) => {
try {
rl.question(theQuestion + ": ", theAnswer => resolve(theAnswer));
} catch {
reject("No Answer");
}
})
}
async function start(){
const answers = [];
for (question of questions){
answers.push(await askQuestion(question));
}
const total = answers.reduce((a, b) => {return Number(a) + Number(b)});
console.log( `The sum of array ${answers} is ${total}`);
rl.close();
}
start();
對於那些感興趣的人,我把這個小模塊放在一起,它接受一系列問題並返回一個解析為一系列答案的promise:
const readline = require('readline');
const AskQuestion = (rl, question) => {
return new Promise(resolve => {
rl.question(question, (answer) => {
resolve(answer);
});
});
}
const Ask = function(questions) {
return new Promise(async resolve => {
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let results = [];
for(let i=0;i < questions.length;i++) {
const result = await AskQuestion(rl, questions[i]);
results.push(result);
}
rl.close();
resolve(results);
})
}
module.exports = {
askQuestions: Ask
}
將它保存在一個名為ask.js(或任何你喜歡的)的文件中並使用如下:
const { askQuestions } = require('./ask');
askQuestions([
'What is question 1?',
'What is question 2?',
'What is question 3?'
])
.then(answers => {
// Do whatever you like with the array of answers
});
注意:需要一個轉發器或最新版本的Node,因為它使用了很多ES6功能。
你可以使用遞歸:
var fs = require('fs')
var readline = require('readline')
rl = readline.createInterface({
input : process.stdin,
output : process.stdout
});
var keys = []
function gen(rank){
if(rank > 3)
{
//do whatever u want
var sum_avg = 0
for (i in keys)
{
sum_avg+=Number(keys[i])
}
console.log(sum_avg/3);
return -1;
}
else
{
var place = rank>1 ? "th" : "st"
var total = rank+place
rl.question("Please enter the "+total+ " number :",function(answer){
keys.push(answer)
//this is where the recursion works
gen(rank+1)
})
}
}
//pass the value from where you want to start
gen(1)
我會在異步函數中提出問題並將readline包裝成與Jason上面的方法類似。 雖然代碼略少:)
const readline = require('readline');
rl = readline.createInterface({
input : process.stdin,
output : process.stdout
});
function question(theQuestion) {
return new Promise(resolve => rl.question(theQuestion, answ => resolve(answ)))
}
async function askQuestions(){
var answer = await question("A great question")
console.log(answer);
}
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const q0 = 'What\'s your name? Nicknames are also acceptable :)';
const q1 = 'What\'s an activity you like doing?';
const q2 = 'What do you listen to while doing that?';
const q3 = 'Which meal is your favourite (eg: dinner, brunch, etc.)';
const q4 = 'What\'s your favourite thing to eat for that meal?';
const q5 = 'Which sport is your absolute favourite?';
const q6 = 'What is your superpower? In a few words, tell us what you are amazing at!';
const arr = [q0, q1, q2, q3, q4, q5, q6];
let res = '';
const askQ = i => {
if (i < arr.length) {
rl.question(arr[i], (answer) => {
res += '\n' + answer;
askQ(i + 1);
});
} else {
console.log(`Thank you for your valuable feedback: ${res}`);
rl.close();
}
};
askQ(0);
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const question = (question) => {
return new Promise((resolve, reject) => {
rl.question(question, (answer) => {
resolve(answer)
})
})
}
const main = async () => {
const username = await question('Please enter a username: ');
const password = await question('Please enter a password: ');
console.log("result: ", {
"username" : username,
"password" : password
});
rl.close()
}
main()
我決定簡化 @jc 為希望從問題中獲得輸出的開發人員編寫的代碼。
為了獲得更多優化代碼,我找到了一個 package node-quick-cli
它不支持 require() 以支持將文件名.js 更改為.mjs
import readline from 'node-quick-cli';
var readlineq = new readline();
(async () => {
console.log(await readlineq.question('Question 1 : '));
console.log(await readlineq.question('question 3 : ',{color:"blue"}));
console.log(await readlineq.question('Question 2 : ',{bgcolor:"bgBlue"}));
readlineq.close();
})();
import readline from 'readline'
const CLI = readline.createInterface( { input: process.stdin , output: process.stdout } )
multiLineCI()
async function multiLineCI() {
const credentials = {
server: await new Promise( rsl => CLI.question( 'enter server: ' , ans => rsl( ans ) ) ),
port: await new Promise( rsl => CLI.question( 'enter port: ' , ans => rsl( ans ) ) ),
username: await new Promise( rsl => CLI.question( 'enter username: ' , ans => rsl( ans ) ) ),
password: await new Promise( rsl => CLI.question( 'enter password: ' , ans => rsl( ans ) ) )
}
console.log( credentials )
CLI.close()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.