[Next13] service에서 .json 데이터를 받아오기 (path.join, process.cwd(), readFile)

쿼카쿼카·2023년 6월 6일
0

React / Next

목록 보기
20/34

코드

import { readFile } from "fs/promises";
import path from "path";

export interface Post {
  src: string;
  date: Date;
  title: string;
  des: string;
  tags: string[];
  featured: boolean;
}

export async function getAllPosts(): Promise<Post[]> {
  const filePath = path.join(process.cwd(), 'data', 'posts.json')
  return readFile(filePath, 'utf-8')
  .then<Post[]>(JSON.parse)
  .then(posts => posts.sort((a, b) => a.date > b.date ? -1 : 1))
}

path

  • path에서 import한 path는 경로를 타고 들어가 읽어올 파일을 가져온다.
  • process.cwd()

    • 현재 작업 경로를 나타냄
  • 최상단 data 폴더의 posts.json파일을 읽어온다.

readFile

  • fs/promises에서 import
  • then바로 뒤에 타입 지정해줄 수 있음
  • then(res => JSON.parse(res)로 쓸 땐 위처럼 then(JSON.parse)로 생략 가능

날짜 순으로 정렬

  • 꼭 숫자 형식을 return해야 한다고 해서 삼항 연산자로 숫자 넣어줌
profile
쿼카에요

0개의 댓글