본문 바로가기

coding test

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();
}).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
// 여러 줄 입력받기
const rl = readline.createInterface({
	input: process.stdin,
    output: process.stout,
});

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]]

https://yoon-dumbo.tistory.com/entry/NODEJS-%EA%B8%B0%EB%B0%98%EC%9C%BC%EB%A1%9C-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%ED%92%80%EB%95%8C-%EC%9E%85%EB%A0%A5%EB%B0%9B%EB%8A%94-%EB%B0%A9%EB%B2%95

 

NODE.JS 기반으로 알고리즘 풀때 입력받는 방법

서론 알고리즘 사이트는 여러가지가 있는데 프로그래머스 나 leetCode와 같은 사이트는 자동으로 입력을 처리해주고 함수내 알고리즘 코드만 작성하면 되는거라 입력받는 것에 대한 고민은 따로

yoon-dumbo.tistory.com

 

728x90