Skip to content

Instantly share code, notes, and snippets.

@lstebner
Created March 5, 2014 22:00
Show Gist options
  • Save lstebner/9377540 to your computer and use it in GitHub Desktop.
Save lstebner/9377540 to your computer and use it in GitHub Desktop.
This little helper can save/load data into files for easy access.
module.exports = function(opts){
var fs = require('fs')
,md5 = require('MD5')
,_ = require('underscore')
,cache_helper = {}
,settings = _.extend({
cache_dir: __dirname + '/cache/'
}, opts || {})
,timenow = function(){
return (new Date()).getTime();
}
;
cache_helper.get_contents = function(name){
//get the real filename
var cache_filename = this.generate_filename(name)
//check if the file exists yet
,exists = fs.existsSync(cache_filename)
;
if (exists){
return JSON.parse(fs.readFileSync(cache_filename, 'UTF-8')) || false;
}
else{
return false;
}
};
cache_helper.is_stale = function(name){
var data = this.get_contents(name)
;
if (data){
return timenow() > data.meta.created + data.meta.stale_after;
}
else{
return true;
}
};
cache_helper.generate_filename = function(name, duration){
return settings.cache_dir + name + '.json';
};
cache_helper.generate_meta = function(name, duration){
var meta = {
name: name
,stale_after: duration
,created: (new Date()).getTime()
,touched: null
};
return meta;
}
cache_helper.store = function(data, name, duration, overwrite){
//get the real filename
var cache_filename = this.generate_filename(name, duration)
//check if the file exists yet
,exists = fs.existsSync(cache_filename)
,store_data = {
meta: this.generate_meta(name, duration)
,data: data
}
;
//we only want to store if it doesn't exist yet or it does and we have
//permission to overwrite it. we should also check if it has expired
if (!exists || (exists && overwrite)){
fs.open(cache_filename, 'w', function(err, fd){
fs.write(fd, JSON.stringify(store_data));
});
}
};
cache_helper.fetch = function(name, fn){
var file_data = this.get_contents(name)
;
if (file_data){
return file_data.data;
}
else{
return false;
}
};
//purge - or remove - existing cache files
//can take a @partial_match value which will be used to check filenames and only
//those containing the @partial_match will be removed
cache_helper.purge = function(partial_match){
var files = fs.readdirSync(settings.cache_dir)
,files_removed = 0
;
_.each(files, function(filename){
var remove = !partial_match;
//simple partial match
if (partial_match){
remove = filename.toLowerCase().indexOf(partial_match.toLowerCase()) > -1;
}
if (remove){
fs.unlinkSync(settings.cache_dir + filename);
files_removed++;
}
});
console.log('cache purge complete.', files.length + ' cache files found,', files_removed + ' files purged');
};
return cache_helper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment