AllRightJunyoung / blog-project

Next.js를 사용하여 개인블로그 만들기
https://www.physicaljun.blog/
2 stars 0 forks source link

[성능] 로컬에 있는 md 파일 읽기 #22

Closed AllRightJunyoung closed 11 months ago

AllRightJunyoung commented 11 months ago

메인 페이지

스크린샷 2023-10-15 오후 4 46 19

게시글 페이지 스크린샷 2023-10-15 오후 4 47 02

비동기적으로 파일을 읽었을떄 메인페이지 90ms , 게시글페이지 12~16ms

소스코드

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

import matter from "gray-matter"; import type { PostsType } from "../types"; import { cache } from "react";

const postsDirectory = path.join(process.cwd(), "src/app/content");

export const getPostData = async (postId: string): Promise => { const postSlug = postId.replace(/.md$/, ""); const filePath = path.join(postsDirectory, ${postSlug}.md); const fileContent = await readFile(filePath, "utf8");

const { data, content } = matter(fileContent);

const postData = { slug: postSlug, ...data, content, } as PostsType;

return postData; }; export const getAllPosts = cache(async (): Promise<PostsType[]> => { const postFiles = await fs.readdir(postsDirectory);

const allPosts = await Promise.all( postFiles.map(async (postFile) => { return getPostData(postFile); }), );

const sortedPosts = allPosts.sort((postA, postB) => postA.date > postB.date ? -1 : 1, );

return sortedPosts; }); `

메인 페이지 스크린샷 2023-10-15 오후 7 28 02

게시글 페이지 스크린샷 2023-10-15 오후 7 28 37

동기적으로 파일을 읽었을떄 메인페이지 4ms ~ 9ms, 게시글페이지 0.9 ~ 4ms

소스 코드

import fs from "fs"; import path from "path"; import matter from "gray-matter"; import type { PostsType } from "../types"; import { cache } from "react";

const postsDirectory = path.join(process.cwd(), "src/app/content");

export const getPostData = cache((postId: string): PostsType => { const postSlug = postId.replace(/.md$/, ""); const filePath = path.join(postsDirectory, ${postSlug}.md); const fileContent = fs.readFileSync(filePath, "utf-8");

const { data, content } = matter(fileContent);

const postData = { slug: postSlug, ...data, content, } as PostsType; return postData; }); export const getAllPosts = cache(() => { const postFiles = fs.readdirSync(postsDirectory);

const allPosts = postFiles.map((postFile) => { return getPostData(postFile); });

const sortedPosts = allPosts.sort((postA, postB) => postA.date > postB.date ? -1 : 1, );

return sortedPosts; });