sandip4069
sandip4069

Reputation: 61

How to use static variable in node js?

I am try to load country names and want to save them in static variable. So that I do not hit in my database again and again. I am using express Js. Please suggest me How can i load country name in optimize ways

Upvotes: 1

Views: 446

Answers (1)

Ritesh Kumar Gupta
Ritesh Kumar Gupta

Reputation: 5191

In node.js, modules are cached after the first time they are loaded. Every call to import/require will retrieve exactly the same object. A good way to achieve this is:

app.js

var app = require('express')(),
    server = require('http').createServer(app);
var lookup=require('./lookup.js');

server.listen(80, function() {
    //Just one init call
    lookup.callToDb(function(){
       console.log('ready to go!');
    });

});

lookup.js

callToDb(function (country){
  module.exports=country;
});

and wherever you require: model.js

var countryLookup= require('./lookup.js');

Upvotes: 2

Related Questions