Created
August 10, 2013 17:15
-
-
Save vodolaz095/6201232 to your computer and use it in GitHub Desktop.
NodeJS modules are singletons
This file contains 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
//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); | |
} | |
This file contains 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
var mem = require('./mem.js'); | |
mem.set('a',100,function(){}); | |
var mem1 = require('./mem.js'); | |
mem1.get('a',function(err,value){ | |
console.log(value); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run by