forked from nodejs/nodejs.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformNodeBlogPosts.js
72 lines (52 loc) · 1.9 KB
/
transformNodeBlogPosts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const fs = require('fs');
const fsPromises = require('fs/promises');
const path = require('path');
// eslint-disable-next-line import/no-extraneous-dependencies
const metadataParser = require('markdown-yaml-metadata-parser');
const commandLineArgs = process.argv.slice(2);
const getMarkdownFilesPath = args => {
return args.length ? args[0] : '.';
};
const markdownPath = getMarkdownFilesPath(commandLineArgs);
const openMarkdownFile = async filename => {
return fsPromises.readFile(path.join(__dirname, markdownPath, filename), {
encoding: 'utf-8',
});
};
const processMarkdownFile = (originalSlug, source) => {
const { content, metadata } = metadataParser(source);
const dateFromMetadata = new Date(metadata.date);
const dateString = dateFromMetadata.toISOString().split('T')[0];
const newFileName = `${dateString}-${originalSlug}.md`;
const blogAuthors = metadata.author
? `['${metadata.author}']`
: `['node-js-website']`;
const newContent = `---
title: ${metadata.title}
blogAuthors: ${blogAuthors}
category: '${metadata.category.toLowerCase()}'
---
${content}`;
return { content: newContent, filename: newFileName };
};
if (fs.existsSync(markdownPath)) {
const filenames = fs.readdirSync(path.join(__dirname, markdownPath));
const markdownFilesFromDirectory = filenames.filter(
filename =>
filename.toLowerCase().includes('.md') &&
!filename.toLowerCase().includes('index.md')
);
const outDir = path.join(__dirname, markdownPath, 'out');
fs.mkdirSync(outDir);
Promise.all(
markdownFilesFromDirectory.map(async filename => {
const source = await openMarkdownFile(filename);
const originalSlug = filename.toLowerCase().replace('.md', '');
const { content, filename: newFileName } = processMarkdownFile(
originalSlug,
source
);
return fsPromises.writeFile(path.join(outDir, newFileName), content);
})
);
}