Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

주니어에서 시니어로

[Javascript] readline 본문

STUDY/Javascript

[Javascript] readline

_JJ_ 2023. 5. 2. 10:58

조금씩 알고리즘 테스트 푸는 연습을 하면서 공부를 하고 있다.

그런데 문제를 풀다가 생소한 용어가 나왔다. readline..?


readline?

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

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

 

The following simple example illustrates the basic use of the node:readline module.

import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';

const rl = readline.createInterface({ input, output });

const answer = await rl.question('What do you think of Node.js? ');

console.log(`Thank you for your valuable feedback: ${answer}`);

rl.close();

- Node.js 공식 문서

 

Readline | Node.js v20.0.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

 

 

공식 문서에는 이렇게 나와 있으나 검색해보니 대부분 저거랑 조금 다르게 쓰고 있었다🤔

 

기본 사용법

// 모듈 가져오기
const readline = require('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
});

let input = [];

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

 

 

 

 

 

reference

https://lakelouise.tistory.com/140

'STUDY > Javascript' 카테고리의 다른 글

[Javascript] 커링 함수란?  (0) 2023.06.21
가비지 컬렉션 (Garbage Collection) 이란?  (0) 2023.04.18
[HTML/Javascript] 오디오 재생  (0) 2023.04.14
[Javascript] 두 배열 비교  (0) 2023.04.12
스코프(Scope)  (0) 2023.04.07