UNPKG

json-file-database

Version:

Lightweight Database on NodeJS by JSON Files

37 lines (36 loc) 1.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createObjectFile = exports.createFile = void 0; const fs_1 = require("fs"); /** * Creates a real file in the disk. * @param path the path of file. * @returns the file for the database to read. */ function createFile(path) { return { read() { return (0, fs_1.readFileSync)(path, 'utf-8'); }, write(content) { (0, fs_1.writeFileSync)(path, content); }, }; } exports.createFile = createFile; /** * Creates a "file" of an object. * @param obj the content object. * @param mutable whether the object is mutable, if so, it will be assigned whenever data updates. * @returns the file for the database to read. */ function createObjectFile(obj, mutable = false) { const file = { read: () => JSON.stringify(obj), write: () => { }, }; if (mutable) file.write = content => Object.assign(obj, JSON.parse(content)); return file; } exports.createObjectFile = createObjectFile;