readline 모듈
readline 모듈은 Node.js 환경에서 사용되는 모듈로, 사용자와 상호작용하며 터미널에서 입력을 받을 수 있게 해줍니다. 이 모듈을 사용하면 터미널에서 한 줄씩 입력을 읽을 수 있고, 사용자로부터의 입력을 받아서 처리할 수 있습니다.
1. readline 모듈 불러오기
readline 모듈을 사용하기 위해서는 Node.js를 설치해야 합니다. Node.js를 설치한 후에는 다음과 같이 readline 모듈을 가져올 수 있습니다
const readline = require('readline');
2. 인터페이스 생성하기
readline 모듈을 사용하려면 먼저 readline.Interface 객체를 생성해야 합니다. readline.Interface 객체는 터미널에서 사용자의 입력을 처리하는 인터페이스 역할을 합니다. 아래는 readline 모듈을 사용하여 readline.Interface 객체를 생성하는 예제입니다
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
3. 입출력을 처리하는 코드 작성하기
readline.createInterface 함수는 input과 output 옵션을 받습니다. input은 입력 스트림으로, 일반적으로 process.stdin을 사용하여 표준 입력을 지정합니다. output은 출력 스트림으로, 일반적으로 process.stdout을 사용하여 표준 출력을 지정합니다.
readline.Interface 객체를 생성한 후에는 rl.question() 메서드를 사용하여 사용자에게 질문을 할 수 있습니다. rl.question() 메서드는 첫 번째 인자로 질문을 받으며, 두 번째 인자로 사용자의 입력을 처리하는 콜백 함수를 받습니다. 아래는 rl.question() 메서드를 사용하는 예제입니다
rl.question('What is your name? ', (answer) => {
console.log(`Hello, ${answer}!`);
rl.close();
});
위 예제에서는 사용자에게 "What is your name?"이라는 질문을 하고, 사용자의 입력을 answer 매개변수로 받아서 처리합니다. 입력을 받은 후에는 입력된 내용을 출력하고, rl.close() 메서드를 호출하여 readline 인터페이스를 닫습니다.
rl.question() 메서드를 호출한 이후에는 사용자의 입력을 기다리면서 다른 작업을 할 수 있습니다. 사용자의 입력이 준비되면 콜백 함수가 호출되어 입력을 처리합니다.
위의 예제에서는 입력을 한 번만 받고 rl.close()를 호출하여 인터페이스를 닫았지만, 만약 계속해서 입력을 받고 싶다면 rl.question() 메서드를 콜백 함수 내에서 재귀적으로 호출하면 됩니다.
이외에도 readline 모듈은 다양한 기능을 제공합니다. 예를 들어, rl.setPrompt() 메서드를 사용하여 프롬프트 메시지를 변경할 수 있고, rl.on('line', callback) 이벤트를 사용하여 한 줄씩 입력을 처리할 수 있습니다.
[출처] Node.js 공식 문서 : https://nodejs.org/dist/latest-v18.x/docs/api/readline.html
Readline | Node.js v18.16.0 Documentation
Readline# Source Code: lib/readline.js The node:readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. To use the promise-based APIs: import * as readline from 'node:readline/promises';cons
nodejs.org