메인페이지에 가장 최근 포스트순으로 카드형식으로 6개 ~ 9개 정도를 보여주거나 인피니티 스크롤을 사용해서 날짜순으로 보여주려고 한다.
이런식으로 위에서부터 최근 포스트 순서대로 보여줄것이다
const getLatelyPosts = (files = [], dir = process.cwd() + '/posts') => {
fs.readdirSync(dir).map((v, i) => {
const tempDir = path.join(dir, v);
if (isDirectory(tempDir)) {
getLatelyPosts(files, tempDir);
} else {
const fileStats = fs.statSync(tempDir);
if (files[files.length] === undefined) {
files[files.length] = {};
}
const offset = new Date().getTimezoneOffset() * 60000;
const createDate = new Date(fileStats.birthtime - (offset)).toISOString().replace(/T/, ' ').split(" ");
const modifyDate = new Date(fileStats.mtime - (offset)).toISOString().replace(/T/, ' ').split(" ");
files[files.length - 1].fileName = v.split(".md")[0].replace(/\_/g,' ');
files[files.length - 1].createDate = createDate[0];
files[files.length - 1].modifyDate = modifyDate[0];
}
});
files.sort((a, b) => {
return new Date(b.modifyDate) - new Date(a.modifyDate);
});
return {
files
};
};
기존에 사용했던 파일 정보를 가져오는 소스를 약간 수정해서 위와같이 변경해주고 마지막엔 파일들의 날짜 내림차순으로 정렬을 해줬다. 로그를 찍어보면 아래와같이 날짜별로 정렬이 되어있는것을 확인 할 수 있다.
{
files: [
{
fileName: 'test',
createDate: '2022-12-18',
modifyDate: '2023-01-05'
},
{
fileName: 'React Hook 이란?',
createDate: '2022-12-18',
modifyDate: '2022-12-23'
},
{
fileName: 'ts',
createDate: '2022-12-18',
modifyDate: '2022-12-18'
},
{
fileName: 'nonblocking',
createDate: '2022-12-18',
modifyDate: '2022-12-18'
}
]
}
markdown
으로 블로그를 개발하다보면 해당 마크다운 페이지에 태그도 추가해야하고 해당 게시글에대한 요약같은 정보를 담을곳이 필요한데 이때 사용하기 쉬운 라이브러리가 있다. 바로 gray-matter
이다. 우선 설치해주자
npm i gray-matter
로 설치 후 markdown 내용을 가져왔던곳에서 matter()로 감싸주면 된다.
우선 마크다운 최상단부분에 아래와같이 메타데이터 정보들을 입력해주자
---
site: asdf
test: test
thumb: asdf
tags:
- a
- b
---
그다음 아래와같이 해당 마크다운파일의 메타데이터를 gray-matter
라이브러리를 사용해서 가져오게되면 아래와같이 변수로 뽑을 수 있다.
const fileContent = fs.readFileSync(tempDir, 'utf8');
const frontMatter = matter(fileContent).data;
{ site: 'asdf', test: 'test', thumb: 'asdf', tags: [ 'a', 'b' ] }
결과 :::
gray-matter
의 라이브러리를 몰라서 마크다운에 주석을 추가하고 포스팅 페이지에서 그 주석을 불러와 사용하려고 하다보니 상당히 오래걸렸다