코드
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해야 한다고 해서 삼항 연산자로 숫자 넣어줌