1- import fs from "fs" ;
1+ import fs from "fs/promises " ;
22import path from "path" ;
33import matter from "gray-matter" ;
44import { remark } from "remark" ;
@@ -14,11 +14,9 @@ async function getBlog(
1414 const blogDirectory = path . join ( process . cwd ( ) , "app/blog/posts" ) ;
1515 const filePath = path . join ( blogDirectory , `${ slug } .md` ) ;
1616
17- if ( ! fs . existsSync ( filePath ) ) {
18- return notFound ( ) ;
19- }
17+ await fs . access ( filePath ) ;
2018
21- const fileContent = fs . readFileSync ( filePath , "utf-8" ) ;
19+ const fileContent = await fs . readFile ( filePath , "utf-8" ) ;
2220 const { data : rawData , content } = matter ( fileContent ) ;
2321
2422 const data = BlogSchema . parse ( rawData ) ;
@@ -63,27 +61,38 @@ export default async function BlogPost({ params }: Params) {
6361 </ div >
6462 ) ;
6563 } catch ( error ) {
64+ console . error ( "Error rendering blog post:" , error ) ;
6665 return notFound ( ) ;
6766 }
6867}
6968
7069export async function generateStaticParams ( ) {
71- const posts = fs
72- . readdirSync ( path . join ( process . cwd ( ) , "app/blog/posts" ) )
73- . filter ( ( filename ) => filename . endsWith ( ".md" ) )
74- . map ( ( filename ) => ( {
75- slug : filename . replace ( / \. m d $ / , "" ) ,
76- } ) ) ;
77-
78- return posts ;
70+ try {
71+ const files = await fs . readdir ( path . join ( process . cwd ( ) , "app/blog/posts" ) ) ;
72+ return files
73+ . filter ( ( filename ) => filename . endsWith ( ".md" ) )
74+ . map ( ( filename ) => ( {
75+ slug : filename . replace ( / \. m d $ / , "" ) ,
76+ } ) ) ;
77+ } catch ( error ) {
78+ console . error ( "Error generating static params:" , error ) ;
79+ return [ ] ;
80+ }
7981}
8082
8183export async function generateMetadata ( { params } : Params ) : Promise < Metadata > {
82- const { slug } = await params ;
83- const { data } = await getBlog ( slug ) ;
84+ try {
85+ const { slug } = await params ;
86+ const { data } = await getBlog ( slug ) ;
8487
85- return {
86- title : data . title ,
87- authors : [ { name : data . author } ] ,
88- } ;
88+ return {
89+ title : data . title ,
90+ authors : [ { name : data . author } ] ,
91+ } ;
92+ } catch ( error ) {
93+ console . error ( "Error generating metadata:" , error ) ;
94+ return {
95+ title : "Blog Post" ,
96+ } ;
97+ }
8998}
0 commit comments