@alinex/datastore
Version:
Read, work and write data structures from and to differents locations and formats.
60 lines • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.modified = exports.save = exports.load = void 0;
const fs_1 = require("fs");
const debug_1 = require("debug");
const debug = debug_1.default('datastore:protocol:file');
const load = async function (parsedUri, options = {}) {
if (!parsedUri.pathname)
return Promise.reject(`No pathname given in ${parsedUri.href}`);
debug(`loading ${parsedUri.pathname}`);
const meta = { path: parsedUri.pathname };
fs_1.promises
.stat(parsedUri.pathname)
.then(stat => {
meta.stats = stat;
})
.catch(e => undefined);
if (options.tail) {
let lines = 0;
const bufferSize = 4096;
let soFar = Buffer.from('');
let data = Buffer.from('');
const fd = await fs_1.promises.open(parsedUri.pathname, 'r');
let position = meta.stats.size;
while (position && lines < options.tail) {
let buffer = Buffer.alloc(bufferSize);
var length = Math.min(bufferSize, position);
position = position - length;
fs_1.readSync(fd.fd, buffer, 0, length, position);
soFar = Buffer.concat([buffer, soFar]);
let pos = soFar.byteLength;
do {
pos = soFar.lastIndexOf('\n', pos - 1);
lines++;
} while (pos !== -1 && lines < options.tail);
data = Buffer.concat([soFar.slice(pos), data]);
soFar = soFar.slice(0, pos);
}
fd.close();
return Promise.resolve([data.slice(1), meta]);
}
return fs_1.promises.readFile(parsedUri.pathname).then(data => [data, meta]);
};
exports.load = load;
const save = function (parsedUri, buffer, options) {
if (!parsedUri.pathname)
return Promise.reject(`No pathname given in ${parsedUri.href}`);
debug(`storing to ${parsedUri.pathname}`);
return fs_1.promises.writeFile(parsedUri.pathname, buffer);
};
exports.save = save;
const modified = async function (parsedUri, options) {
if (!parsedUri.pathname)
return Promise.reject(`No pathname given in ${parsedUri.href}`);
debug(`last modification check ${parsedUri.pathname}`);
const fileinfo = await fs_1.promises.stat(parsedUri.pathname);
return Promise.resolve(fileinfo.mtime);
};
exports.modified = modified;
//# sourceMappingURL=file.js.map