/** * 文件存储工具 * 将表单数据追加写入 server/storage/ 目录下的 JSON 文件 */ import { promises as fs } from 'fs' import { resolve } from 'path' const STORAGE_DIR = resolve(process.cwd(), 'server/storage') /** * 确保存储目录存在 */ async function ensureDir() { try { await fs.mkdir(STORAGE_DIR, { recursive: true }) } catch { // 目录已存在,忽略 } } /** * 将记录追加到指定文件 * @param {string} filename - 不含路径,如 'customize.json' * @param {object} record */ export async function appendRecord(filename, record) { await ensureDir() const filepath = resolve(STORAGE_DIR, filename) let records = [] try { const raw = await fs.readFile(filepath, 'utf-8') records = JSON.parse(raw) } catch { // 文件不存在或解析失败,从空数组开始 } records.push(record) await fs.writeFile(filepath, JSON.stringify(records, null, 2), 'utf-8') return record } /** * 读取所有记录(管理员用) * @param {string} filename */ export async function readRecords(filename) { const filepath = resolve(STORAGE_DIR, filename) try { const raw = await fs.readFile(filepath, 'utf-8') return JSON.parse(raw) } catch { return [] } }