Advertisement
DaCurse

Node.js simple JSON database

Sep 10th, 2017
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Promise = require('bluebird');
  2. const fs = Promise.promisifyAll(require('fs'));
  3. const path = require('path');
  4. const dbPath = path.join(__dirname, 'db.json');
  5.  
  6. const factoryDefaults = {
  7.   defaultPrefix: ";",
  8.   servers: []
  9. }
  10.  
  11. class Server {
  12.   constructor(id) {
  13.     this.id = id;
  14.   }
  15. }
  16.  
  17. function saveJSON(jsonObject) {
  18.   fs.writeFileSync(dbPath, JSON.stringify(jsonObject, null, 2), 'utf-8');
  19. }
  20.  
  21. function getDB() {
  22.   return new Promise(async resolve => {
  23.     let data = await fs.readFileAsync(dbPath);
  24.     try {
  25.       let json = JSON.parse(data);
  26.       resolve(json);
  27.     } catch (ex) {
  28.       saveJSON(factoryDefaults);
  29.       resolve(factoryDefaults);
  30.     }
  31.   });
  32. }
  33.  
  34. function getValue(key) {
  35.   return new Promise(async resolve => {
  36.     let json = await getDB();
  37.     if (typeof json[key] !== "undefined")
  38.       resolve(json[key]);
  39.     else throw new Error(`Key ${key} doesn't exist in the database.`);
  40.  });
  41. }
  42.  
  43. function editValue(key, value) {
  44.  return new Promise(async resolve => {
  45.    let db = await getDB();
  46.    db[key] = value;
  47.    saveJSON(db);
  48.  });
  49. }
  50.  
  51. module.exports = {
  52.  getDB: getDB,
  53.  getValue: getValue,
  54.  editValue: editValue
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement