Skip to content

Instantly share code, notes, and snippets.

@vodolaz095
Created August 10, 2013 17:15
Show Gist options
  • Save vodolaz095/6201232 to your computer and use it in GitHub Desktop.
Save vodolaz095/6201232 to your computer and use it in GitHub Desktop.
NodeJS modules are singletons
//A memory cache client for nodeJS
//It leaks memory and not scalable, DO NOT USE IN PRODUCTION!
//2 methods are utilized
// .get(key,function(err,value){})
// .set(key,value,function(err,resultOfSaving){},timeToLiveInMilliseconds)
var Storage = {};
exports.get = function (key, callback) {
if (Storage[key]) {
var now = new Date().getTime();
if (Storage[key].expireAt > now) {
callback(null, Storage[key].value);
} else {
delete Storage[key];
Storage[key] = null;
callback(null, null);
}
} else {
callback(null, null);
}
}
exports.set = function (key, value, callback, ttlInMs) {
if (ttlInMs && /^\d+$/.test(ttlInMs)) {
var expireAt = new Date().getTime() + ttlInMs;
} else {
var expireAt = new Date().getTime() + 60000;
}
Storage[key] = {'value':value, 'expireAt':expireAt};
callback(null, true);
}
var mem = require('./mem.js');
mem.set('a',100,function(){});
var mem1 = require('./mem.js');
mem1.get('a',function(err,value){
console.log(value);
});
@vodolaz095
Copy link
Author

Run by

 $ node memtest.js

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