본문 바로가기
웹 개발

마크다운 파일(.md)을 데이터로 추출 및 HTML로 변환

by xosoy 2023. 7. 10.

마크다운 파일을 데이터로 추출하는 방법은 다음과 같다.

 

우선 gray-matter을 설치한다: npm install gray-matter --save

 

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

const postsDirectory = path.join(process.cwd(), 'posts');

export function getSortedPostsData() {
  const fileNames = fs.readdirSync(postsDirectory);//['pre-rendering.md', ...]
  
  const allPostsData = fileNames.map(fileName => {
    const id = fileName.replace(/\.md$/, "");

    const fullPath = path.join(postsDirectory, fileName);
    const fileContents = fs.readFileSync(fullPath, 'utf-8');

    const matterResult = matter(fileContents);
    
    return {
      id,
      ...allPostsData(matterResult.data as { date: string, title: string})
    }
  })

  return allPostsData.sort((a,b) => {
    if (a.date < b.date) {
      return 1;
    } else {
      return -1;
    }
  })
}

process.cwd 메소드는 프로젝트의 경로를 반환한다.

readdirSync는 인자로 들어간 경로에 존재하는 파일 이름을 배열로 반환한다.

'.md'를 제거하기 위해 replace 메소드의 첫번째 인자에 /\.md$/ 를 넣어준다. (/는 이스케이프 문자, $는 ~로 끝남을 의미한다)

readFileSync로 파일을 읽고, matter 메소드로 파일 내용(string)을 객체(object)로 얻는다. 

md 파일

이런 형태의 파일이면 객체의 data 프로퍼티에는 title, date를 프로퍼티로 가지는 객체가 있고, content 프로퍼티에는 파일 내용이 있다. 

 

gray-matter에 대해서는 아래 링크를 참고하자.

https://www.npmjs.com/package/gray-matter

 

 

 

추출한 마크다운 데이터를 HTML로 변환하는 방법은 다음과 같다.

  const fullPath = path.join(postsDirectory, `${id}.md`);
  const fileContents = fs.readFileSync(fullPath, 'utf-8');

  const matterResult = matter(fileContents);

  const processedContent = await remark().use(remarkHtml).process(matterResult.content);
  const contentHtml = processedContent.toString();

변환한 HTML은 현재 string으로 되어 있다. 이를 진짜 HTML로 바꾸어 주려면 다음과 같이 사용하면 된다.

<div dangerouslySetInnerHTML={{ __html: post.contentHtml }} />

 

'웹 개발' 카테고리의 다른 글

비동기 프로그래밍  (0) 2024.03.08
Virtual DOM과 (Real) DOM의 차이  (0) 2024.03.05
GraphQL 기초  (0) 2023.09.18
localStorage와 sessionStorage  (0) 2023.08.20
Greedy Algorithm  (0) 2023.07.05