sbjw
2025-08-13 7e6f1330b41769f638b6699e6104aa82f1794f03
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
const fs = require('fs');
const path = require('path');
 
// 1. 配置源代码目录和输出目录
const SOURCE_DIR = path.resolve(__dirname, './src/example/');
const OUTPUT_DIR = path.resolve(__dirname, './public/example/');
 
// 2. 递归查找所有以 Page.js 结尾的文件
function findPageJsFiles(dir) {
    const files = fs.readdirSync(dir);
    let pageJsFiles = [];
 
    files.forEach(file => {
        const fullPath = path.join(dir, file);
        const stat = fs.statSync(fullPath);
 
        if (stat.isDirectory()) {
            // 如果是目录,递归查找
            pageJsFiles = pageJsFiles.concat(findPageJsFiles(fullPath));
        } else if (file.endsWith('Page.js') && file !== 'ExamplePage.js') {
            // 如果是 Page.js 文件,添加到结果中
            pageJsFiles.push(fullPath);
        }
    });
 
    return pageJsFiles;
}
 
// 3. 生成 Markdown 内容
function generateMarkdown(code, filePath) {
    const fileName = path.basename(filePath, '.js');
    return `
### ${fileName} 代码
 
\`\`\`jsx
${code}
\`\`\`
`;
}
 
// 4. 主函数
function main() {
    // 确保输出目录存在
    if (!fs.existsSync(OUTPUT_DIR)) {
        fs.mkdirSync(OUTPUT_DIR, { recursive: true });
    }
 
    // 查找所有 Page.js 文件
    const pageJsFiles = findPageJsFiles(SOURCE_DIR);
 
    if (pageJsFiles.length === 0) {
        console.log('⚠️ 未找到任何以 Page.js 结尾的文件');
        return;
    }
 
    console.log(`🔍 找到 ${pageJsFiles.length} 个 Page.js 文件:`);
    pageJsFiles.forEach(file => console.log(`  - ${file}`));
 
    // 处理每个文件
    pageJsFiles.forEach(filePath => {
        try {
            // 读取源代码
            const code = fs.readFileSync(filePath, 'utf8');
 
            // 生成 Markdown 内容
            const mdContent = generateMarkdown(code, filePath);
 
            // 确定输出路径(保持相对路径结构)
            const relativePath = path.relative(SOURCE_DIR, filePath);
            const outputFilePath = path.join(OUTPUT_DIR, relativePath.replace(/\.js$/, '.md'));
 
            // 确保输出目录存在
            const outputDir = path.dirname(outputFilePath);
            if (!fs.existsSync(outputDir)) {
                fs.mkdirSync(outputDir, { recursive: true });
            }
 
            // 写入 Markdown 文件
            fs.writeFileSync(outputFilePath, mdContent);
 
            console.log(`✅ 已生成: ${outputFilePath}`);
        } catch (error) {
            console.error(`❌ 处理文件 ${filePath} 时出错:`, error.message);
        }
    });
}
 
// 执行主函数
main();