Last active
September 30, 2020 13:00
-
-
Save samermurad/523f7a4c16ef95826d0e3478400218db to your computer and use it in GitHub Desktop.
Tmp Cache for NodeJs scripts, very useful for small program where you might want to persist some data for later reuse
This file contains hidden or 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
// Written by Samer Murad | |
const path = require('path'); | |
const fs = require('fs'); | |
const os = require('os'); | |
class TmpCache { | |
constructor(ID) { | |
this.FILE_ID = ID; | |
this.TMP_DIR = os.tmpdir(); | |
} | |
get filePath() { | |
return path.join(this.TMP_DIR, `${this.FILE_ID}.json`); | |
} | |
async save() { | |
const data = {...this}; | |
delete data.FILE_ID; | |
delete data.TMP_DIR; | |
fs.writeFileSync(this.filePath, JSON.stringify(data, undefined, 2), 'utf8'); | |
} | |
async load() { | |
if (fs.existsSync(this.filePath)) { | |
try { | |
const jsonStr = fs.readFileSync(this.filePath, 'utf8').toString(); | |
const json = JSON.parse(jsonStr); | |
Object.keys(json).forEach(key => { | |
this[key] = json[key] | |
}) | |
} catch (e) { | |
// no cache found | |
// noop | |
} | |
} | |
} | |
} | |
module.exports = TmpCache; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage: