NestJS, 파일 읽기

2021. 6. 24. 09:40개발/Node

Node에서 파일 읽기는 fs를 사용합니다.

https://nodejs.org/api/fs.html

 

File system | Node.js v16.4.0 Documentation

 

nodejs.org

 

보통은 readFile을 이용해서 읽고 처리를 (저 같은 경우는) 많이 하지만, readFile 이후에 해당 파일을 사용하기 쉽지 않습니다.

왜냐하면 비동기로 읽기 때문입니다. (Asynchronously reads the entire contents of a file.)

fs.readFile('src/quiz/quiz.txt', 'utf8', function (err, data) {
    if (err) throw err;
  
    console.log(data);
});

 

동기로 처리하기 위해서는 readFileSync를 이용합니다.

const quiz = fs.readFileSync('src/quiz/quiz.txt', 'utf8');
console.log(quiz);

 

이걸 이용해서 NestJS에서는 해당 라인의 파일을 읽어오는 Get 방식 구조를 아래와 같이 작성할 수 있습니다.

@Get('question/:id')
getQuizQuestion(@Param('id') id: number) {
    return this.quizService.getQuizQuestion(+id);
}
getQuizQuestion(id: number) {
    const file = fs.readFileSync('src/quiz/quiz.txt', 'utf8');
    const quiz = file.split('\n');

    return quiz[id - 1];
}