[Node.js] 자바스크립트 콘솔에서 입력 받는 방법
글 작성자: 망고좋아
반응형

🎯 Node.js 콘솔창 입력받기
- 백준에서 알고리즘 문제를 풀 때 자바스크립트 입력받는 방법을 알아보자!
📝 한 줄 값 입력받기
- 자바스크립트에서는
readline
모듈을 이용하면 콘솔을 통해 값을 입력받을 수 있다.
📕 모듈 가져오기
const readline = require("readline");
📕 readline
모듈을 이용해 입출력을 위한 인터페이스 객체 생성
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, });
📕 rl
변수
rl.on("line", (line) => { // 한 줄씩 입력받은 후 실행할 코드 // 입력된 값은 line에 저장된다. rl.close(); // 필수!! close가 없으면 입력을 무한히 받는다. }); rl.on('close', () => { // 입력이 끝난 후 실행할 코드 process.exit(); })
한 줄 입력받기 :: 정리
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.on("line", (line) => { console.log("input: ", line); rl.close(); }); rl.on('close', () => { process.exit(); })
📝 공백을 기준으로 값 입력받기
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); let input = [] rl.on("line", (line) => { input = line.split(' ').map(el => parseInt(el)); // 1 2 3 4 rl.close(); }); rl.on('close', () => { input.forEach(el => { console.log(el); }) process.exit(); }) // 입력 // 1 2 3 // 출력 // 1 // 2 // 3

- 입력되는 것은 모두 문자열이기 때문에 숫자 연산을 할 수 없다. 따라서 숫자 연산을 위해 map() 함수를 사용하고 parseInt()를 이용해 모든 문자를 숫자로 변환해준다.
📝 여러 줄 입력받기
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); let input = [] rl.on("line", (line) => { input.push(line); }); rl.on('close', () => { console.log(input); process.exit(); }) // 입력 // 1 // 2 // a // b // 출력 // ['1', '2', 'a', 'b']
- 입력 종료는
ctrl + c

📝 공백이 포함된 문자 여러 줄 입력받기
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); let input = [] rl.on("line", (line) => { input.push(line.split(' ').map(el => parseInt(el))); }); rl.on('close', () => { console.log(input); process.exit(); }) // 입력 // 1 2 3 // 4 5 6 // 출력 // [[1, 2, 3], [4, 5, 6]]

📌 참고
반응형
'프로그래밍 > Node.js' 카테고리의 다른 글
[Node.js] Node.js 모듈의 작성과 사용 (0) | 2021.12.02 |
---|---|
[Node.js] Node.js 모듈 (0) | 2021.12.02 |
[Node.js] npm과 npx는 무엇인가? (0) | 2021.12.02 |
[Node.js] Node.js 이벤트 루프 (0) | 2021.12.02 |
[Node.js] Node.js 특징 (0) | 2021.12.02 |
댓글
이 글 공유하기
다른 글
-
[Node.js] Node.js 모듈
[Node.js] Node.js 모듈
2021.12.02 -
[Node.js] npm과 npx는 무엇인가?
[Node.js] npm과 npx는 무엇인가?
2021.12.02 -
[Node.js] Node.js 이벤트 루프
[Node.js] Node.js 이벤트 루프
2021.12.02 -
[Node.js] Node.js 특징
[Node.js] Node.js 특징
2021.12.02
댓글을 사용할 수 없습니다.