const readline = require('readline');
const rl = readline.createInterface({
input : process.stdin,
output : process.stdout,
});
rl.question('query:string', (data) => {
// 입력값에 대한 처리
console.log(data);
rl.close()
});
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let a, b;
rl.question('첫 번째 값을 입력하세요: ', (data1) => {
a = Number(data1); // 첫 번째 입력 값을 숫자로 변환
rl.question('두 번째 값을 입력하세요: ', (data2) => {
b = Number(data2); // 두 번째 입력 값을 숫자로 변환
console.log(`입력한 값: ${a}, ${b}`);
rl.close(); // 입력 종료
});
});
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const inputs = [];
const questions = ['첫 번째 값을 입력하세요: ', '두 번째 값을 입력하세요: ', '세 번째 값을 입력하세요: '];
const askQuestion = (index) => {
if (index === questions.length) {
console.log(`입력한 값: ${inputs.join(', ')}`);
rl.close();
return;
}
rl.question(questions[index], (data) => {
inputs.push(Number(data)); // 입력값을 숫자로 변환 후 저장
askQuestion(index + 1); // 다음 질문 실행
});
};
askQuestion(0); // 첫 번째 질문부터 시작
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const askQuestion = () => {
rl.question('입력하세요: ', answer => {
if (/* 입력 조건 검사 */ false) {
console.log('조건에 맞지 않아요. 다시 입력하세요.');
askQuestion(); // 재귀 호출
} else {
console.log(`입력값: ${answer}`);
rl.close(); // 입력이 유효하면 종료
}
});
};
askQuestion(); // 최초 호출
readline
모듈 불러오기js
CopyEdit
const readline = require('readline');
readline
을 가져옴.readline.createInterface()
를 사용하여 인터페이스 생성js
CopyEdit
const rl = readline.createInterface({
input : process.stdin,
output : process.stdout,
});
readline.createInterface()
를 호출하여 rl
이라는 인터페이스 객체를 생성.input: process.stdin
: 표준 입력(키보드 입력)을 받음.output: process.stdout
: 표준 출력(터미널에 출력)을 사용함.rl.question()
을 사용하여 사용자 입력 받기js
CopyEdit
rl.question('query:string', (data) => {
// 입력값에 대한 처리
console.log(data);
rl.close();
});
rl.question(prompt, callback)
형태로 사용.'query:string'
→ 사용자에게 보여줄 질문.(data) => { ... }
→ 사용자가 입력한 값이 data
에 저장되고 콜백 함수 내부에서 처리됨.console.log(data);
→ 입력받은 값을 터미널에 출력.rl.close();
→ 입력을 완료한 후 readline
인터페이스를 닫음.query:string
이 콘솔에 표시됨.Enter
를 누르면, 입력한 값이 data
에 저장됨.console.log(data);
를 통해 출력됨.rl.close();
가 실행되면서 입력 인터페이스가 종료됨.$ node script.js
query:string hello
hello
query:string
이 먼저 출력됨.hello
를 입력하면 hello
가 출력됨.rl.close()
를 사용해야 하는 이유rl.createInterface()
는 입력을 지속적으로 받을 수 있도록 process.stdin
을 유지함.rl.close()
를 호출하지 않으면 프로그램이 종료되지 않고 계속 대기 상태가 됨.rl.on('line', callback)
을 사용한 여러 줄 입력rl.question()
은 한 번 입력을 받으면 종료되지만, 여러 줄을 받을 때는 rl.on('line', callback)
을 사용할 수 있음.
js
CopyEdit
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on('line', (data) => {
console.log(`입력한 값: ${data}`);
});
Ctrl + C
또는 process.exit(0);
을 호출해야 종료됨.