UNPKG

devilfish-dbms

Version:

a database that based on key-value map and is successful in deal with saved in disk and high-performance in select that act as a memory-based database

64 lines (59 loc) 1.86 kB
const fs = require('fs'); const path = require('path'); function repairJSONDBFile(dbFilePath) { let raw; try { raw = fs.readFileSync(dbFilePath, 'utf8'); } catch (err) { console.error('读取数据库文件失败:', err.message); return false; } // 先尝试直接解析 try { JSON.parse(raw); console.log('数据库文件未损坏,无需修复'); return true; } catch (e) { // 继续修复 } // 尝试从尾部裁剪,找到能被JSON.parse解析的最大前缀 let lastGood = null; let lastGoodStr = ''; let step = 1; for (let i = raw.length; i > 0; i -= step) { let candidate = raw.slice(0, i); // 尝试补全右大括号 let fixed = candidate; let leftCount = (fixed.match(/{/g) || []).length; let rightCount = (fixed.match(/}/g) || []).length; if (leftCount > rightCount) { fixed += ']]}}'.repeat(leftCount - rightCount); } try { let obj = JSON.parse(fixed); lastGood = obj; lastGoodStr = fixed; break; } catch (e) { // 继续裁剪 } } if (lastGood) { // 备份原始文件 fs.copyFileSync(dbFilePath, dbFilePath + '.bak'); // 写入修复文件 fs.writeFileSync(dbFilePath + '.repaired', lastGoodStr, 'utf8'); console.log('已修复数据库文件,修复版为:' + dbFilePath + '.repaired'); return true; } else { console.log('无法修复数据库文件'); return false; } } // 用法 const dbFile = process.argv[2]; if (!dbFile) { console.log('用法: node repairdb.js yourdb.db'); process.exit(1); } repairJSONDBFile(dbFile);