
백준에서 JS로 문제 풀기
백준에서 자바스크립트(node.js)로 문제를 풀려면 입출력을 직접 해줘야 한다.
fs 모듈 사용
fs 모듈은 FileSystem의 약자로 파일 처리와 관련된 모듈이다.
파일 읽기
fs.readFileSync(filename, [options]) (동기적) filename의 파일을 [options] 방식으로 읽은 후 문자열을 반환한다.
코드가 한 줄인 경우
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().split(' ');
코드가 여러 줄인 경우
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().split('\n');
VSCode에서 문제 풀기
일단 npm이나 yarn으로 fs 모듈을 설치 해준다.
$ npm install fs
or
$ yarn add fs
예시로 10869번 사칙 연산 문제를 풀어보면서 익혀보자.
같은 폴더 내부에 txt 파일을 하나 생성하고 예제를 복사해 저장한다.

10869.js 파일에서 readFileSync
의 filename을 예제를 저장한 txt 파일로 바꿔준다. console.log를 찍어보면 [ ‘7’, ‘3’ ]와 같이 배열로 저장된 것을 확인할 수 있다.
// 10869.js
const fs = require('fs');
let input = fs.readFileSync('test.txt').toString().split(' ');
console.log(input); // [ '7', '3' ]
배열의 원소를 변수에 저장하고 풀면 된다. 예제 출력 결과와 실행한 결과가 같게 코드를 작성해야 한다.
const fs = require('fs');
let input = fs.readFileSync('test.txt').toString().split(' ');
const a = Number(input[0]);
const b = Number(input[1]);
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(parseInt(a / b));
console.log(a % b);

백준 제출하기
제출할 때는 readFileSync의 filename을 /dev/stdin
으로 바꿔준다.
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().split(' ');
const a = Number(input[0]);
const b = Number(input[1]);
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(parseInt(a / b));
console.log(a % b);

제출 버튼을 눌러주면 결과를 확인할 수 있다.

References
Table Of Contents