批量整理 Markdown 文件
文章目录

实际上逻辑很简单: 首先读取所有文件夹下面的markdown文件然后,然后整理格式,然后写回去

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
const path = require("path");
const fs = require("fs");
const dj = require("doctor-jones");
const getPathInfo = (p) => path.parse(p);

const PATH = "../posts";

/**
* @description // 递归读取文件,类似于webpack的require.context()
* @time 2020-9-12
*
* @param {String} directory 文件目录
* @param {Boolean} useSubdirectories 是否查询子目录
* @param {array} extList 查询文件后缀
*
*/
function autoLoadFile(directory, useSubdirectories = true, extList = [".md"]) {
const filesList = [];
// 递归读取文件
function readFileList(directory, useSubdirectories, extList) {
const files = fs.readdirSync(directory);
files.forEach((item) => {
const fullPath = path.join(directory, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory() && useSubdirectories) {
readFileList(path.join(directory, item), useSubdirectories, extList);
} else {
const info = getPathInfo(fullPath);
extList.includes(info.ext) && filesList.push(fullPath);
}
});
}
readFileList(directory, useSubdirectories, extList);
// 生成需要的对象
const res = filesList.map((item) => {
return {
path: item,
// data: require(item),
...getPathInfo(item),
};
});

return res;
}

const fileList = autoLoadFile(path.join(__dirname, PATH));

fileList.map(async (e) => {
const raw = await fs.readFileSync(e.path, "utf8");

const formated = dj(raw, {
ellipsisTolerance: "all",
spaceBetweenFullwidthPunctuationAndAlphabets: false,
});
await fs.writeFileSync(e.path, formated);
});