fix(dev): 读取本地 JSON 时剥离 UTF-8 BOM 并捕获解析异常
外部编辑器/同步工具写入的 data/*.json 带有 BOM,直接 JSON.parse 会抛错并导致 vite dev server 退出。现在统一剥离 BOM,解析失败时返回 500 而非中断进程。
This commit is contained in:
+9
-3
@@ -103,9 +103,15 @@ const localFileStoragePlugin = () => {
|
|||||||
const filePath = path.join(dataDir, `${safeKey}.json`);
|
const filePath = path.join(dataDir, `${safeKey}.json`);
|
||||||
|
|
||||||
if (fs.existsSync(filePath)) {
|
if (fs.existsSync(filePath)) {
|
||||||
const data = fs.readFileSync(filePath, 'utf-8');
|
try {
|
||||||
res.setHeader('Content-Type', 'application/json');
|
// 文件可能带 UTF-8 BOM(外部编辑器/同步工具写入),解析前需剥离,否则 JSON.parse 抛错
|
||||||
res.end(JSON.stringify({ success: true, data: JSON.parse(data) }));
|
const raw = fs.readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, '');
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
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 {
|
} else {
|
||||||
res.statusCode = 404;
|
res.statusCode = 404;
|
||||||
res.end(JSON.stringify({ success: false, error: 'Not found' }));
|
res.end(JSON.stringify({ success: false, error: 'Not found' }));
|
||||||
|
|||||||
Reference in New Issue
Block a user