fix(dev): 读取本地 JSON 时剥离 UTF-8 BOM 并捕获解析异常

外部编辑器/同步工具写入的 data/*.json 带有 BOM,直接 JSON.parse 会抛错并导致 vite dev server 退出。现在统一剥离 BOM,解析失败时返回 500 而非中断进程。
This commit is contained in:
2026-10-24 08:11:21 +08:00
committed by trae-solo-agent
parent 5aaa39d292
commit 5cdfc70818
+8 -2
View File
@@ -103,9 +103,15 @@ const localFileStoragePlugin = () => {
const filePath = path.join(dataDir, `${safeKey}.json`);
if (fs.existsSync(filePath)) {
const data = fs.readFileSync(filePath, 'utf-8');
try {
// 文件可能带 UTF-8 BOM(外部编辑器/同步工具写入),解析前需剥离,否则 JSON.parse 抛错
const raw = fs.readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, '');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ success: true, data: JSON.parse(data) }));
res.end(JSON.stringify({ success: true, data: JSON.parse(raw) }));
} catch (e) {
res.statusCode = 500;
res.end(JSON.stringify({ success: false, error: e.message }));
}
} else {
res.statusCode = 404;
res.end(JSON.stringify({ success: false, error: 'Not found' }));