Implemented atomic writes for json database

This commit is contained in:
Trevor Mears
2026-01-03 23:29:32 -08:00
parent dd95c6f6ed
commit bd9106be49
+7 -1
View File
@@ -72,15 +72,21 @@ function getDefaultSettings() {
// Write lock to prevent concurrent writes from corrupting db.json // Write lock to prevent concurrent writes from corrupting db.json
let writeQueue = Promise.resolve(); let writeQueue = Promise.resolve();
const tmpPath = dbPath + '.tmp';
async function saveDb(data) { async function saveDb(data) {
// Queue this write operation - each write waits for the previous one // Queue this write operation - each write waits for the previous one
writeQueue = writeQueue.then(async () => { writeQueue = writeQueue.then(async () => {
try { try {
const jsonString = JSON.stringify(data, null, 2); const jsonString = JSON.stringify(data, null, 2);
await fs.writeFile(dbPath, jsonString); // Atomic write: write to temp file, then rename
// Rename is atomic on most filesystems, preventing corruption on crash
await fs.writeFile(tmpPath, jsonString);
await fs.rename(tmpPath, dbPath);
} catch (err) { } catch (err) {
console.error('Error writing database:', err); console.error('Error writing database:', err);
// Clean up temp file if it exists
try { await fs.unlink(tmpPath); } catch { /* ignore */ }
throw err; throw err;
} }
}).catch(err => { }).catch(err => {