1
1
// Node.js 脚本:自动扫描 leetcode md 文件,生成 leetcode-index.js
2
2
const fs = require ( 'fs' ) ;
3
3
const path = require ( 'path' ) ;
4
- const mdDir = path . join ( __dirname , 'leetcode' ) ;
4
+ // 修正为项目 src/posts/leetcode 目录
5
+ const mdDir = path . resolve ( __dirname , '../../../../posts/leetcode' ) ;
5
6
const outFile = path . join ( __dirname , 'leetcode-index.js' ) ;
6
7
7
8
function getMeta ( content ) {
@@ -11,9 +12,18 @@ function getMeta(content) {
11
12
match [ 1 ] . split ( '\n' ) . forEach ( line => {
12
13
if ( / ^ t i t l e : / . test ( line ) ) meta . title = line . replace ( 'title:' , '' ) . trim ( ) ;
13
14
if ( / ^ d a t e : / . test ( line ) ) meta . date = line . replace ( 'date:' , '' ) . trim ( ) ;
14
- if ( / ^ c a t e g o r i e s : / . test ( line ) ) meta . categories = JSON . parse ( line . replace ( 'categories:' , '' ) . replace ( / ' / g, '"' ) . trim ( ) ) ;
15
- if ( / ^ t a g s : / . test ( line ) ) meta . tags = JSON . parse ( line . replace ( 'tags:' , '' ) . replace ( / ' / g, '"' ) . trim ( ) ) ;
15
+ if ( / ^ c a t e g o r i e s : / . test ( line ) ) {
16
+ meta . categories = line . replace ( 'categories:' , '' )
17
+ . replace ( '[' , '' ) . replace ( ']' , '' )
18
+ . split ( ',' ) . map ( s => s . trim ( ) ) . filter ( Boolean ) ;
19
+ }
20
+ if ( / ^ t a g s : / . test ( line ) ) {
21
+ meta . tags = line . replace ( 'tags:' , '' )
22
+ . replace ( '[' , '' ) . replace ( ']' , '' )
23
+ . split ( ',' ) . map ( s => s . trim ( ) ) . filter ( Boolean ) ;
24
+ }
16
25
} ) ;
26
+
17
27
// 简要描述,取 # 题目 下第一段
18
28
const descMatch = content . match ( / # [ \u4e00 - \u9fa5 \w ] + \n + ( [ \s \S ] * ?) ( \n { 2 , } | $ ) / ) ;
19
29
meta . desc = descMatch ? descMatch [ 1 ] . replace ( / \r / g, '' ) . trim ( ) : '' ;
@@ -30,7 +40,9 @@ function scanMdFiles(dir) {
30
40
const content = fs . readFileSync ( fullPath , 'utf-8' ) ;
31
41
const meta = getMeta ( content ) ;
32
42
if ( meta ) {
33
- meta . url = path . relative ( mdDir , fullPath ) . replace ( / \\ / g, '/' ) ;
43
+ // 生成 html 路径
44
+ const relPath = path . relative ( mdDir , fullPath ) . replace ( / \\ / g, '/' ) ;
45
+ meta . url = relPath . replace ( / \. m d $ / , '.html' ) ;
34
46
result . push ( meta ) ;
35
47
}
36
48
}
0 commit comments