UNPKG

kool-save-data

Version:

A simple save data module for my Node.js projects.

39 lines (31 loc) 863 B
'use-strict'; const fs = require('fs'), path = require('path'), logger = require('kool-logger'); class SaveData { constructor(id, data = {}) { this.id = id; this.data = data; this.fileName = `${id}.json`; } modifyData(data) { Object.assign(this.data, data); } save(dataPath, data = this.data) { dataPath = path.resolve(dataPath); fs.writeFileSync(path.join(dataPath, this.fileName), JSON.stringify(data, null, 4)); } getSaved(dataPath) { dataPath = path.resolve(dataPath); try { return JSON.parse(fs.readFileSync(path.join(dataPath, this.fileName))); } catch (err) { logger.error(`Error getting save data:\n${err.stack}`); return err; } } load(dataPath) { this.data = this.getSaved(dataPath); } } module.exports = SaveData;