Node.js 환경에서 사용자 입력을 받는 기능을 제공해 주는 readline 모듈에 대해 살펴보겠습니다.
다음은 nodejs.org의 공식 문서화 사이트에 있는 설명입니다.
The
node:readlinemodule provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time
제공된 인터페이스를 통해 한번에 한 줄씩 사용자 입력을 받을 수 있는 모듈이라는 것을 알 수 있습니다.
readline 모듈을 사용하기 위해서는 readline.Interface 클래스의 인스턴스를 생성할 필요가 있습니다. 인터페이스 객체를 선언 시에 stdin과 stdout을 입출력으로 입력해 줍니다.
const readline = require('readline');
const { stdin: input, stdout: output } = require('process');
const rl = readline.createInterface({ input, output });
생성된 인스턴스는 다음과 같은 이벤트들을 받습니다.
line 이벤트는 개행문자('\n', '\r', '\r\n')를 입력받을 때 발생합니다. 이를 이용해 한줄 단위로 사용자 입력을 받을 수 있습니다.
rl.on('line', (line) => {
console.log(`Received: ${line}`);
rl.close();
});
Hello
Received: Hello
입력받은 내용을 출력한 뒤엔 close 메서드를 호출하여 인스턴스를 종료해 줍니다.
또는 once 메서드를 입력을 한번만 받을 수도 있습니다. 이벤트가 발생한 후에는 이벤트 리스너가 종료됩니다.
rl.once('line', (line) => {
console.log(line);
});
close 이벤트는 인스턴스가 종료될 때 발생합니다.
rl.on('line', (line) => {
// do something
rl.close();
}).on('close', () => {
// close event function
});
이 외에도 'history', 'pause', 'resume', 'SIGINT' 등의 이벤트가 있습니다.
const lines = [];
rl.on('line', (line) => {
lines.push(line);
});
rl.once('line', (line1) => {
rl.once('line', (line2) => {
console.log(`${line1} ${line2}`);
}
});
rl.question('What is your favorite fruit? ', (answer) =>
console.log(`My favorite fruit would be ${answer}.`);
rl.close();
});
What is your favorite fruit? mango
My favorite fruit would be mango.
rl.setPrompt('What is your favorite fruit?> ');
rl.prompt();
rl.on('line', (line) => {
console.log(line);
rl.close();
});
What is your favorite fruit?> mango
mango
nodejs.org - Readline