英文:
How to use static variable in node js?
问题
我正在尝试加载国家名称并希望将它们保存在静态变量中,以便我不再反复访问我的数据库。
我正在使用Express 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
答案1
得分: 1
在Node.js中,模块在第一次加载后会被缓存。每次调用import/require都会获取到完全相同的对象。
一个好的方法是:
app.js
var app = require('express')(),
server = require('http').createServer(app);
var lookup = require('./lookup.js');
server.listen(80, function() {
// 只有一次初始化调用
lookup.callToDb(function(){
console.log('ready to go!');
});
});
lookup.js
callToDb(function (country){
module.exports = country;
});
无论在哪里进行require:
model.js
var countryLookup = require('./lookup.js');
英文:
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');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论