-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreate-page.js
100 lines (85 loc) · 2.41 KB
/
create-page.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
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
98
99
100
#!/usr/bin/env node
// module
import fs from "node:fs";
import path from "node:path";
const [, , pageName, ...args] = process.argv;
// arg prase
const options = {
categories: [],
tags: [],
section: [],
};
for (const arg of args) {
if (arg.startsWith("-")) {
const option = arg.slice(1);
const value = args[args.indexOf(arg) + 1];
if (option === "h" || option === "help") {
console.log(`Usage: create-page <page-name> [options]`);
console.log("");
console.log("Options:");
console.log(" -c, --categories <categories> Comma-separated list of categories");
console.log(" -t, --tags <tags> Comma-separated list of tags");
console.log(" -s, --section <section> Section name");
console.log(" -h, --help Display this help message");
console.log(` usage: npm run create-page "技术分享随笔" -s "note" -c "note" -t "JavaScript"`);
process.exit(0);
} else if (option === "c" || option === "categories") {
options.categories = value.split(",");
} else if (option === "t" || option === "tags") {
options.tags = value.split(",");
} else if (option === "s" || option === "section") {
options.section = value.split(",");
} else {
console.error(`Invalid option: ${arg}`);
process.exit(1);
}
}
}
// check pageName
if (!pageName) {
console.error("请输入页面名称");
process.exit(1);
}
const date = new Date().toISOString().split("T")[0];
const [year, month, day] = date.split("-");
// Format time
const time = new Date().toLocaleTimeString("zh-CN", {
hour: "numeric",
minute: "numeric",
// second: "numeric",
hour12: false,
});
// format dir Path
const dirPath = path.resolve(
"docs",
...options.section.map((section) => section.toString()),
year.toString(),
month.toString(),
day.toString()
);
// mkdir
try {
await fs.promises.mkdir(dirPath, { recursive: true });
} catch (err) {
console.error(err);
process.exit(1);
}
const fullDate = `${date} ${time}`;
// insert the content prepared
const content = `---
title: ${pageName}
date: ${fullDate}
categories: [${options.categories.join(", ")}]
tags: [${options.tags.join(", ")}]
copyright: true
---
`;
const filePath = path.resolve(dirPath, `${pageName}.md`);
// operation
fs.writeFile(filePath, content, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`页面 ${dirPath}/${pageName}.md 创建成功!`);
});