nodedb-json
Version:
A lightweight JSON-based database for Node.js with TypeScript support, indexing, and complex query capabilities
58 lines • 2.07 kB
JavaScript
import * as fs from 'fs';
import { cleanupTempFile, ensureParentDirectory, writeFileAtomic } from './atomic-writer.js';
import { CorruptedFileError } from '../errors/corrupted-file-error.js';
export class JsonFileStorage {
constructor(filePath, options) {
this.filePath = filePath;
this.options = options;
}
read() {
ensureParentDirectory(this.filePath);
cleanupTempFile(this.options.tempPath);
if (!fs.existsSync(this.filePath)) {
if (this.options.createIfNotExists) {
this.write(JSON.stringify(this.options.defaultValue || {}, null, 2));
}
else {
throw new Error(`Database file does not exist: ${this.filePath}`);
}
}
return this.readWithBackup();
}
write(content, backupOnWrite = true) {
if (!this.options.atomicWrites) {
ensureParentDirectory(this.filePath);
fs.writeFileSync(this.filePath, content, 'utf-8');
return;
}
writeFileAtomic(this.filePath, content, {
backupOnWrite: backupOnWrite && this.options.backupOnWrite,
backupPath: this.options.backupPath,
tempPath: this.options.tempPath
});
}
readWithBackup() {
try {
return readJsonFile(this.filePath);
}
catch (error) {
if (!fs.existsSync(this.options.backupPath)) {
throw new CorruptedFileError(this.filePath, error);
}
let backupData;
try {
backupData = readJsonFile(this.options.backupPath);
}
catch (backupError) {
throw new CorruptedFileError(this.filePath, backupError);
}
this.write(JSON.stringify(backupData, null, 2), false);
return backupData;
}
}
}
export function readJsonFile(filePath) {
const fileData = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(fileData);
}
//# sourceMappingURL=json-file-storage.js.map