Skip to content

Instantly share code, notes, and snippets.

@brandoncorbin
Created August 21, 2019 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandoncorbin/faa0d1bc7b398cdd7e4cc0380924cef8 to your computer and use it in GitHub Desktop.
Save brandoncorbin/faa0d1bc7b398cdd7e4cc0380924cef8 to your computer and use it in GitHub Desktop.
A simple storage solution in Node.
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