개발-IT/NEXTJS

정리2

바다로그 2020. 12. 18. 13:23
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'

const postsDirectory = path.join(process.cwd(),'posts')
//https://nodejs.org/api/path.html#path_path_join_paths
//https://nodejs.org/api/process.html#process_process_cwd
 
export function getSortedPostsData(){
    //get filename under /posts
    //https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options 
    const fileNames = fs.readdirSync(postsDirectory) 
    const allPostsData = fileNames.map(fileName => {
        
        //remove ".md" from file name to get id.  
        const id = fileName.replace(/\.md$/,'')
      
        //read markdown file as strings
        const fullPath = path.join(postsDirectory,fileName)
        const fileContents = fs.readFileSync(fullPath,'utf8')
 
        //use gray-matter to parse the post meta data section  
           //https://www.npmjs.com/package/gray-matter
        const matterResult = matter (fileContents) 
     
        return{
            id, 
            fileName,
            ...matterResult.data 
        }
    })
    return allPostsData.sort( (a,b) => { 
        if(a.date < b.date){
            return 1
        } else {
            return -1
        }
    })  
}

'개발-IT > NEXTJS' 카테고리의 다른 글

nextjs 강의 목록  (0) 2020.12.10