import { readdirSync, readFileSync, writeFileSync } from "fs"; import { join, dirname } from "path"; import { fileURLToPath } from "url"; interface ColorItem { "color-name": string; color: string; } interface ColorCollection { [folderName: string]: ColorItem[]; } const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); function extractColorsFromHtml(html: string): ColorItem[] { const colors: ColorItem[] = []; const colorItemRegex = /
  • ]*>.*?
    ]*>([^<]+)<\/div>.*?]*>(#[A-Fa-f0-9]{6})<\/span>.*?<\/li>/gs; let match; while ((match = colorItemRegex.exec(html)) !== null) { const colorName = match[1].trim(); const hexColor = match[2]; if (colorName && hexColor) { colors.push({ "color-name": colorName, color: hexColor }); } } return colors; } function getAllHtmlFiles(): string[] { const htmlFiles: string[] = []; function scanDirectory(dir: string) { const entries = readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = join(dir, entry.name); if (entry.isDirectory()) { scanDirectory(fullPath); } else if (entry.isFile() && entry.name === "像素格子.html") { htmlFiles.push(fullPath); } } } scanDirectory(join(__dirname, "pages-list")); return htmlFiles; } function getFolderName(htmlFilePath: string): string { const relativePath = htmlFilePath.replace(join(__dirname, "pages-list"), "").replace(/\\/g, "/"); const parts = relativePath.split("/").filter(p => p.length > 0); if (parts.length > 0 && parts[parts.length - 1] === "像素格子.html") { return parts.slice(0, -1).join("/") || "root"; } return parts[0] || "unknown"; } function main() { console.log("开始解析HTML文件..."); const htmlFiles = getAllHtmlFiles(); console.log(`找到 ${htmlFiles.length} 个HTML文件`); const colorCollection: ColorCollection = {}; for (const htmlFile of htmlFiles) { try { const htmlContent = readFileSync(htmlFile, "utf-8"); const colors = extractColorsFromHtml(htmlContent); const folderName = getFolderName(htmlFile); if (colors.length > 0) { colorCollection[folderName] = colors; console.log(`✓ ${folderName}: 提取了 ${colors.length} 个颜色`); } else { console.log(`✗ ${folderName}: 未找到颜色数据`); } } catch (error) { console.error(`✗ 处理文件失败: ${htmlFile}`, error); } } const outputPath = join(__dirname, "colors.json"); writeFileSync(outputPath, JSON.stringify(colorCollection, null, 2), "utf-8"); console.log(`\n数据已保存到: ${outputPath}`); console.log(`总共处理了 ${Object.keys(colorCollection).length} 个颜色集合`); console.log(`总颜色数量: ${Object.values(colorCollection).reduce((sum, colors) => sum + colors.length, 0)}`); } main();