Skip to content

Instantly share code, notes, and snippets.

@samermurad
Last active September 30, 2020 13:00
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 samermurad/523f7a4c16ef95826d0e3478400218db to your computer and use it in GitHub Desktop.
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
// 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;
@samermurad
Copy link
Author

Example Usage:

const TmpCache = require('./tmpCache');
const tmpCache = new TmpCache('ID_OF_TMP_FILE');


const run = async () => {
    await tmpCache.load();
    console.log('Last provided was:', tmpCache.anyValueWithAnyName);
    tmpCache.anyValueWithAnyName = new Date().getTime();
    await tmpCache.save();
    console.log('Run Script again to get the cached value!');
};

// running file as main
if (__filename === process.argv[1]) {
  run()
    .then(() => console.log("Done!"))
    .catch(console.error);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment