Implemented atomic writes for json database
This commit is contained in:
+7
-1
@@ -72,15 +72,21 @@ function getDefaultSettings() {
|
||||
|
||||
// Write lock to prevent concurrent writes from corrupting db.json
|
||||
let writeQueue = Promise.resolve();
|
||||
const tmpPath = dbPath + '.tmp';
|
||||
|
||||
async function saveDb(data) {
|
||||
// Queue this write operation - each write waits for the previous one
|
||||
writeQueue = writeQueue.then(async () => {
|
||||
try {
|
||||
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) {
|
||||
console.error('Error writing database:', err);
|
||||
// Clean up temp file if it exists
|
||||
try { await fs.unlink(tmpPath); } catch { /* ignore */ }
|
||||
throw err;
|
||||
}
|
||||
}).catch(err => {
|
||||
|
||||
Reference in New Issue
Block a user