JavaScript/프로그래머스

[프로그래머스/JS] Lv0. 문자열 출력하기 (입출력)

동구름이 2024. 6. 21. 14:12

문제

https://school.programmers.co.kr/learn/courses/30/lessons/181952?language=javascript

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


풀이

네이버 부스트캠프를 준비하며, 2차 시험인 자바스크립트에 익숙해지기 위해 가장 기초적인 문제부터 해결해보았습니다.

 

프론트를 다루면서 자바스크립트를 사용한 경험이 있는데, 코테로는 완전히 색다른 느낌이었습니다.

 

 

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
});

 

우선 처음 이런 코드가 주어지는데, 하나하나를 분석해보면 아래와 같습니다.

 

 

(1) readline 모듈

readline모듈은 readable 스트림에서 한 줄씩 입출력을 처리할 수 있게 도와주는 모듈입니다.

 

 

(2) 모듈을 불러오기

const readline = require('readline');

 

모듈을 불러올 때에는 require("모듈 이름")을 통해 불러오고, 변수를 선언해서 저장합니다.

 

 

(3) readline 인터페이스 객체

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

readline 인터페이스 객체를 통해 표준 입출력을 처리합니다. createInterface 메서드로 객체를 만들어 rl 변수에 저장한 모습입니다.

 

(4) on 메서드, line, close 이벤트

rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
});

on 메서드는 이벤트 발생시 실행할 동작을 지정합니다.

 

그리고 line이벤트는 사용자가 콘솔에 입력할 때, close이벤트는 readable 스트림 종료를 제어합니다.

 

여기서 입력 이벤트는 줄바꿈 제어 문자가 나타나거나 사용자가 enter를 누를 때 발생합니다.

 

 


소스 코드

1.

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
}).on('line', console.log);

 

2.

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
    console.log(str);
});