刘涛 a25f3a77ce sync: 同步最新呼籁官网代码到仓库
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 21:57:35 +08:00

57 行
1.2 KiB
JavaScript

/**
* 文件存储工具
* 将表单数据追加写入 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 []
}
}