Created
August 21, 2019 01:30
-
-
Save brandoncorbin/faa0d1bc7b398cdd7e4cc0380924cef8 to your computer and use it in GitHub Desktop.
A simple storage solution in Node.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
/** | |
* let store = new Storage('path/to/file') | |
* store.put('name', 'Brandon') | |
* store.put('config', { key: 1 }) | |
* let obj = store.get('config'); // { key: 1 } | |
**/ | |
module.exports = class Storage { | |
constructor(file) { | |
this.file = file; | |
if (fs.existsSync(this.file)) { | |
let fileContent = fs.readFileSync(this.file, 'UTF-8') || null; | |
this.data = JSON.parse(fileContent); | |
} else { | |
fs.writeFileSync(this.file, '{}', 'UTF-8'); | |
this.data = {}; | |
} | |
} | |
put(key, value) { | |
this.data[key] = value; | |
this.save(); | |
} | |
get(key) { | |
return this.data[key]; | |
} | |
delete(key) { | |
delete this.data[key]; | |
return this.save(); | |
} | |
save() { | |
return fs.writeFileSync(this.file, JSON.stringify(this.data), 'UTF-8'); | |
} | |
destroy() { | |
return fs.unlinkSync(this.file); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment