/
index.ts
97 lines (73 loc) · 2.48 KB
/
index.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#! /usr/bin/env node
const { parse: xmlParse } = require("fast-xml-parser");
const { readFileSync, writeFileSync, existsSync, mkdirSync } = require("fs");
const glob = require("glob");
const path = require("path");
const usage = (): void => {
console.log(`Usage:
jugem-xml-to-md [target dir]
Description:
This is a CLI tool to convert JUGEM-XML to markdown format.
`);
};
const convertMd = (json: any): Array<object> => {
let mdList = [];
// TODO: entry is Array<entryObject>
const { entry } = json.blog.entries;
if (!entry.length) return [];
for (const e of entry) {
const { title, description, author, category, date } = e;
mdList.push({
title,
description: description.substr(1, 100),
author,
category,
date,
body: description
});
}
return mdList;
};
const generateMd = (mdList: any): void => {
/*
* TODO:
* エクスポートしたXMLデータの場合、画像パスが実際のサイト上で指しているものとは違うものが吐き出される。このパスにアクセスしても画像自体は見つからず404が返される。
* そのため、変換の合間に古い画像パスから現在の画像パスに変換する処理を挟む。
* (途中で画像パスの仕様が変わったのだが、エクスポート機能は未対応ということなのだろうか?)
*/
const disableImagePath = "{古い画像パス}";
const availableImagePath = "{新しい画像パス}";
for (const md of mdList) {
const data = `---
title: ${md.title}
date: ${md.date}
category: ${md.category}
description: ${md.description}
---
${md.body.replace(disableImagePath, availableImagePath)}`;
writeFileSync(`result/${md.title.replace(/\//g, "-")}.md`, data);
}
};
(async () => {
if (["-h", "--help"].includes(process.argv[2])) {
usage();
return;
}
console.log("START: generate markdown files");
const reusltDir = "result";
if (!existsSync(reusltDir)) {
mkdirSync(reusltDir);
}
const targetDif = process.argv[2] || "xml-data";
const xmlFilePathList = glob.sync(path.join(targetDif, "*.xml"));
for (const xmlPath of xmlFilePathList) {
console.log(`processing file ===> ${xmlPath}`);
const xml = await readFileSync(xmlPath, "utf8");
const json = xmlParse(xml);
if (!json) continue;
const mdList = convertMd(json);
if (!mdList) console.log("FINISH: Not found blog data");
generateMd(mdList);
}
console.log("FINISH: generate markdown files");
})();