| 1 | import fs from 'node:fs' |
| 2 | import path from 'node:path' |
| 3 | import { debuglog } from 'node:util' |
| 4 | import { getErrorMessage } from './error.util' |
| 5 | |
| 6 | const log = debuglog('app:preload-files') |
| 7 | |
| 8 | /** |
| 9 | * 同步地从环境变量中读取配置并创建文件。 |
| 10 | */ |
| 11 | function loadFilesFromEnvSync(): void { |
| 12 | log(`${JSON.stringify(process.env, null, 2)}`) |
| 13 | log('开始同步检查并创建文件...') |
| 14 | |
| 15 | const indexSet = new Set<number>() |
| 16 | for (const key of Object.keys(process.env)) { |
| 17 | const m = key.match(/^WRITE_FILE_(\d+)_PATH$/) |
| 18 | if (m && process.env[key]) { |
| 19 | indexSet.add(Number(m[1])) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | const indices = Array.from(indexSet).sort((a, b) => a - b) |
| 24 | |
| 25 | if (indices.length === 0) { |
| 26 | log('未找到任何需要创建的文件环境变量 (例如 \'WRITE_FILE_0_PATH\')。') |
| 27 | return |
| 28 | } |
| 29 | |
| 30 | for (const index of indices) { |
| 31 | const prefix = `WRITE_FILE_${index}_` |
| 32 | const filePath = process.env[`${prefix}PATH`] |
| 33 | |
| 34 | if (!filePath) { |
| 35 | log(`[警告] 索引 %d 缺少 PATH,已跳过。`, index) |
| 36 | continue |
| 37 | } |
| 38 | |
| 39 | const encoding = (process.env[`${prefix}ENCODING`] || 'utf8').toLowerCase() |
| 40 | |
| 41 | if (!(['ascii', 'utf8', 'utf-8', 'utf16le', 'utf-16le', 'ucs2', 'ucs-2', 'base64', 'base64url', 'latin1', 'binary', 'hex']).includes(encoding)) { |
| 42 | log(`[警告] 不支持的编码方式 '%s',已跳过文件 '%s'。`, encoding, filePath) |
| 43 | continue |
| 44 | } |
| 45 | let content = process.env[`${prefix}CONTENT`] |
| 46 | if (content === undefined) { |
| 47 | const contentChunks: string[] = [] |
| 48 | let chunkIndex = 0 |
| 49 | while (true) { |
| 50 | const chunk = process.env[`${prefix}CONTENT_${chunkIndex}`] |
| 51 | if (chunk === undefined) { |
| 52 | break |
| 53 | } |
| 54 | contentChunks.push(chunk) |
| 55 | chunkIndex++ |
| 56 | } |
| 57 | |
| 58 | if (contentChunks.length > 0) { |
| 59 | content = contentChunks.join('') |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | if (content === undefined) { |
| 64 | log(`[警告] 找到文件路径 '%s' 但缺少内容 (缺少 %s),已跳过。`, filePath, `${prefix}CONTENT`) |
| 65 | continue |
| 66 | } |
| 67 | |
| 68 | log(`正在处理文件索引 %d: '%s' (编码: %s)`, index, filePath, encoding) |
| 69 | |
| 70 | try { |
| 71 | const parentDir = path.dirname(filePath) |
| 72 | if (parentDir && parentDir !== '.') { |
| 73 | fs.mkdirSync(parentDir, { recursive: true }) |
| 74 | } |
| 75 | |
| 76 | const bufferContent = Buffer.from(content, encoding as BufferEncoding) |
| 77 | fs.writeFileSync(filePath, bufferContent) |
| 78 | |
| 79 | log(` -> 文件 '%s' 已成功创建。`, filePath) |
| 80 | } |
| 81 | catch (error) { |
| 82 | const message = getErrorMessage(error) |
| 83 | log(`[错误] 创建文件 '%s' 时出错: %s`, filePath, message) |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | loadFilesFromEnvSync() |
| 89 |