저장된 폴더의 경로
const postsDirectory = join(process.cwd(), '_posts');
// /Users/home/Documents/GitHub/guesung-library/apps/blog/_posts
루트 > _posts폴더에 저장할 것이기에, process.cwd() + _posts를 합쳐줍니다.
<aside> ❗ path.join()
path는 Node.js에서 폴더와 파일의 경로를 지정해주는 모듈이다.
path.join()은 인자로 받은 경로들을 하나의 문자열 형태로 리턴한다.
path.join('/foo/bar', './baz'); // /foo/bar/baz
</aside>
해당 경로에서 모든 파일을 불러온다.
export function getPostSlugs() {
return fs.readdirSync(postsDirectory);
}
// [ 'hello-world.md' ]
<aside> ❗ fs.readdirSync
readdirSync는 폴더 내의 모든 파일을 읽어온다.
</aside>
이제, 1번에서의 폴더로 가 2번에서 얻은 파일들의 내용을 불러온다.
export function getPostBySlug(slug: string) {
const realSlug = slug.replace(/\.md$/, '');
const fullPath = join(postsDirectory, `${realSlug}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
const { data, content } = matter(fileContents);
return { ...data, slug: realSlug, content } as Post;
}
불러온 내용을 정렬하고 가공한다.
export function getAllposts(): Post[] {
const slugs = getPostSlugs();
const posts = slugs
.map(slug => getPostBySlug(slug))
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
return posts;
}