[ node.js ] 자바스크립트 콘솔로 값 입력받기

zaman·2022년 3월 11일
5

ETC

목록 보기
2/3
post-thumbnail

js를 공부하면서 한번도 콘솔로 값을 받아서 사용하는 문제는 풀어지 못했는데 node.js 영역이여서 그랬나보다
이 방법으로 백준에서 js 문제를 풀 수 있다고 하니 정리해보자

📝 readline 모듈

: readline 모듈은 한 번에 한 줄씩 Readable 스트림 (예 : process.stdin)에서 데이터를 읽기위한 인터페이스를 제공

The readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. node document > readline

✔️ 모듈 불러오기

:require(모듈 이름)

const readline = require("readline");

불러온 모듈은 readline이라는 변수에 저장

공홈 사용 예시

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

// createInterface() 메소드를 이용해 객체를 만들고, rl이라는 변수에 저장
const rl = readline.createInterface({ input, output });

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

이 코드가 호출되면 readline.Interface가 닫힐 때 까지 종료되지 않는다 (인터페이스가 입력 스트림에서 데이터가 수신되기를 기다리기 때문)
Once this code is invoked, the Node.js application will not terminate until the readline.Interface is closed because the interface waits for data to be received on the input stream.


✏️ 사용

기본만 알고있으면 나머지는 그냥 js를 사용하는것과 같았다

1. 기본

const readline = require("readline");

const rl = readline.createInterface({
  // 모듈을 이용해 입출력을 위한 인터페이스 객체 생성
  input: process.stdin,
  output: process.stdout,
});

  // 생성한 rl 변수를 사용하는 법
  rl.on("line", (line) => { 
     // 한 줄씩 입력받은 후 실행할 코드
     // 입력된 값은 line에 저장된다.
     console.log(line);
      rl.close(); // close가 없으면 입력을 무한히 받는다.
  });
  rl.on('close', () => {
    // 입력이 끝난 후 실행할 코드
  })

✔️ on 메소드

: 이벤트가 발생할 때 실행할 동작을 지정

rl.on("line", (line) => { ... });

✔️ line 이벤트

: readline interface를 통해 다룰 이벤트, 사용자가 콘솔에 입력을 할 때 발생

  rl.on("line", (line) => { 
     console.log(line);
  });

입력 이벤트는 입력 스트림에 줄바꿈을 나타내는 \n, \r, or \r\n 제어 문자가 나타나거나, 사용자가 Enter 또는 Return을 누를 때 발생
사용자가 입력 이벤트를 발생시키면,line을 통해 사용자가 입력한 내용이 저장되고 이를 콘솔에 출력하는 방식

✔️ close 이벤트

: Readable 스트림 종료를 제어하는 이벤트

  rl.on("line", (line) => { 
     console.log(line);
      rl.close(); // close가 없으면 입력을 무한히 받는다.
  });

2. 한 줄만 입력

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();
});

// > test
// input:  test

2. 공백을 기준으로 한 줄 씩 산출

const readline = require("readline");
 
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
 
let input = []
rl.on("line", (line) => {
    // 공백을 기준으로 
    input = line.split(' '); 
    rl.close();
});
 
rl.on('close', () => {
    input.forEach(el => {
        console.log(el);
    })
    process.exit();
})
// > 1 2 3 (문자열)
// 1
// 2
// 3

3. 여러 줄 입력

const readline = require("readline");

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

let input = [];
rl.on("line", (line) => {
  input.push(line);
  // 받은 input 값인 line을 input 배열에 넣어줌
});

rl.on("close", () => {
  console.log(input); // input 배열 산출
  process.exit();
});
// > 1
// 2
// 3 control + c를 눌러야 종료
// [ '1', '2', '3' ]

4. 여러 줄 입력 & 여러줄 산출

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", () => {
  input.map((v) => console.log(v));
  process.exit();
});
// > 1
// 2
// 3 control + c를 눌러야 종료
// 1
// 2
// 3

5. 공백 포함 여러 줄 입력

const readline = require("readline");

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

let input = [];

rl.on("line", (line) => {
  input.push(line.split(" ")); // 문자열
});

rl.on("close", () => {
  console.log(input);
  process.exit();
});
// > 1 2 3
// > 4 5 6
// [ [ '1', '2', '3' ], [ '4', '5', '6' ] ]





이제 백준 알고리즘도 풀어볼 수 있다!

profile
개발자로 성장하기 위한 아카이브 😎

0개의 댓글