nodedb-json
Version:
A lightweight JSON-based database for Node.js with TypeScript support, indexing, and complex query capabilities
47 lines • 1.29 kB
JavaScript
import * as fs from 'fs';
import * as path from 'path';
export function ensureParentDirectory(filePath) {
const directory = path.dirname(filePath);
if (directory && directory !== '.') {
fs.mkdirSync(directory, { recursive: true });
}
}
export function cleanupTempFile(tempPath) {
if (fs.existsSync(tempPath)) {
fs.unlinkSync(tempPath);
}
}
export function fsyncDirectory(directory) {
try {
const fd = fs.openSync(directory, 'r');
try {
fs.fsyncSync(fd);
}
finally {
fs.closeSync(fd);
}
}
catch (_a) {
// Some platforms/filesystems do not support fsync on directories.
}
}
export function writeFileAtomic(filePath, content, options) {
ensureParentDirectory(filePath);
let fd;
try {
fd = fs.openSync(options.tempPath, 'w');
fs.writeFileSync(fd, content, 'utf-8');
fs.fsyncSync(fd);
}
finally {
if (fd !== undefined) {
fs.closeSync(fd);
}
}
if (options.backupOnWrite && fs.existsSync(filePath)) {
fs.copyFileSync(filePath, options.backupPath);
}
fs.renameSync(options.tempPath, filePath);
fsyncDirectory(path.dirname(filePath));
}
//# sourceMappingURL=atomic-writer.js.map