json-database
A Node.js module for storing data in files on the local machine. It's basically a settings manager.
This is only meant to be used by a single application since it doesn't automatically reload the file after another application has edited it. When it saves the file, it rewrites the entire file to disk.
Install
json-database is available for installation through npm using the npm install
command.
npm install @tusent.io/json-database --save
Usage
const Database = require('json-database');
const db = new Database('./data.json');
let dataVersion = db.get('dataVersion', Number.MIN_SAFE_INTEGER);
let userCount = db.get('userCount', 0);
if (dataVersion < 7) {
db.save(db.path + '.bak');
for (let i = 0; i < userCount; i++) {
let username = db.get(`users.${i}.name`);
if (username !== null) {
db.set(`users.${i}.name`, null);
db.set(`username${i}`, username);
}
}
db.set('dataVersion', 7);
console.log('Updated database to data version 7.');
}
if (dataVersion < 7) {
db.save(db.path + '.bak');
for (let i = 0; i < userCount; i++) {
let username = db.get(`users.${i}.name`);
if (username !== null) {
db.set(`users.${i}.name`, null, false);
db.set(`username${i}`, username, false);
}
}
db.save();
db.set('dataVersion', 7);
console.log('Updated database to data version 7.');
}
Note that I/O errors thrown by the fs-module are not caught and must be caught by the user of this module. The affected methods are Database.save
, Database.set
(unless called with save
parameter set to false
), and Database.constructor
.
License
LGPL-3.0