-
Notifications
You must be signed in to change notification settings - Fork 186
/
csv.js
59 lines (46 loc) · 1.64 KB
/
csv.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
const fs = require("fs").promises;
const path = require("path");
const fm = require("front-matter");
const mdDir = process.env.MARKDOWN_DIR || path.join(__dirname, "lessons/");
const outputPath =
process.env.OUTPUT_FILE || path.join(__dirname, "public/lessons.csv");
async function createCsv() {
console.log(`making the markdown files into a CSV from ${mdDir}`);
// get paths
const allFiles = await fs.readdir(mdDir);
const files = allFiles.filter(filePath => filePath.endsWith(".md"));
// read paths, get buffers
const buffers = await Promise.all(
files.map(filePath => fs.readFile(path.join(mdDir, filePath)))
);
// make buffers strings
const contents = buffers.map(content => content.toString());
// make strings objects
let frontmatters = contents.map(fm);
// find all attribute keys
const seenAttributes = new Set();
frontmatters.forEach(item => {
Object.keys(item.attributes).forEach(attr => seenAttributes.add(attr));
});
const attributes = Array.from(seenAttributes.values());
if (attributes.includes("order")) {
frontmatters = frontmatters.sort(
(a, b) => a.attributes.order - b.attributes.order
);
}
// get all data into an array
let rows = frontmatters.map(item => {
const row = attributes.map(attr =>
item.attributes[attr] ? JSON.stringify(item.attributes[attr]) : ""
);
return row;
});
// header row must be first row
rows.unshift(attributes);
// join into CSV string
const csv = rows.map(row => row.join(",")).join("\n");
// write file out
await fs.writeFile(outputPath, csv);
console.log(`Wrote ${rows.length} rows to ${outputPath}`);
}
createCsv();