-
Notifications
You must be signed in to change notification settings - Fork 139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can I access the cache across different script? #312
Comments
You can create a new file called cache.js somewhere that contains your node-cache initialization and then returns the cache instance. You can then use the returned instance in any other file as it serves as a singleton. // Filename: cache.js
const NodeCache = require( "node-cache" );
const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );
module.exports = {
myCache
} // Filename: test1.js
const { myCache } = require("./cache.js");
const obj = { my: "Special", variable: 42 };
success = myCache.set( "myKey", obj, 10000 ); // Filename: test2.js
const { myCache } = require("./cache.js");
success = myCache.set("anotheKey", "something here", 10000 ); With this the same instance of cache is shared around. |
Thank you so much. If I want to apply something like refreshing the token every 9 hours, is it possible for me to do it like this inside cache.js, or is there any better way to do it? const cache = new NodeCache();
cache.set("token", await getToken(), 9*60*60);
cache.on("del", async function (key, value) {
cache.set("token", await getToken(), 9*60*60);
}); Is |
Yes, that is possible. Inside the file that you require it in, you can still bind events. Although, to answer your question, it is generally better to either place them in the file where you mainly use nodecache in, or if you would like, for better code organization, make a function like const cache = new NodeCache();
// . . .
function registerEvents() {
cache.cache.on("del", (key, value) => {
cache.cache.set(key, "...");
});
} And to answer the second question, |
Let's say I am declaring an
obj
in test1.js.Is it possible to access
"myKey"
in test2.js during running?If yes, how can I do it?
If not, how to access
"myKey"
in some child nested functions? Through multiple passing as the parameter?The text was updated successfully, but these errors were encountered: