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
|
// 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 => {
|
||||||
|
|||||||
Reference in New Issue
Block a user