node-json-db
Version:
Database using JSON file as storage for Node.JS
53 lines • 1.41 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileAdapter = void 0;
const promises_1 = require("fs/promises");
const path = require("path");
class FileAdapter {
filename;
fsync;
constructor(filename, fsync) {
this.filename = filename;
this.fsync = fsync;
}
async readAsync() {
try {
return await (0, promises_1.readFile)(this.filename, {
encoding: 'utf-8'
});
}
catch (e) {
if (e.code === 'ENOENT') {
return null;
}
throw e;
}
}
async writeAsync(data) {
let fd = null;
try {
fd = await (0, promises_1.open)(this.filename, 'w');
}
catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
const basepath = path.dirname(this.filename);
await (0, promises_1.mkdir)(basepath, { recursive: true });
fd = await (0, promises_1.open)(this.filename, 'w');
}
try {
await fd.writeFile(data, {
encoding: 'utf-8'
});
if (this.fsync) {
await fd.sync();
}
}
finally {
await fd.close();
}
}
}
exports.FileAdapter = FileAdapter;
//# sourceMappingURL=FileAdapter.js.map