如何在Node.js中使用静态变量?

huangapple go评论91阅读模式
英文:

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');

huangapple
  • 本文由 发表于 2020年1月6日 19:30:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定