简体   繁体   English

如何在Node.js&Express中使用全局变量(可共享变量)

[英]how to use global variable(sharable variables) in Node.js&Express

I have a file called data.js for keeping data as memory database. 我有一个名为data.js的文件,用于将数据保留为内存数据库。

var express = require('express');
var app = express();

var aList;
var bList;
var cList;

module.exports = app;

And I want to initialise data when I start the server. 而且我想在启动服务器时初始化数据。 So, I implemented init() in app.js 因此,我在app.js实现了init()

...
var data = require('./data'); // data.js is located in the same folder.

app.set(...);
app.use(...);
...

init();

...

});

fun init(){
    console.log("Hello!");

    aList = getDumpDataList(10); // I also tried with 'data.aList = getDumpDataList(10);' but didn't work.

    console.log(JSON.stringify(aList));
}

fun getDumpDataList(n){
    var list;

    ... // for loop to generate random elements.

    return list;
}

module.exports = app;

When I printed with console.log() , Hello! 当我用console.log()打印时, Hello! is printed but aList isn't printed but undefined 被打印但aList不被打印但undefined

And I also want to use the data in routers under routes folder. 我也想在routes文件夹下的路由器中使用数据。

So, what I did is. 所以,我所做的是。

...
var data = require('./data');

route.get("/...", function(req, res, next){
    console.log(JSON.stringify(aList));
    ...
});

But it is also undefined . 但这也是undefined

I am just making simple test server that initialise data whenever I re-run. 我只是做一个简单的测试服务器,每当我重新运行时就初始化数据。

How can I share variables between the js files? 如何在js文件之间共享变量?

You do not export those vars: 您不导出这些变量:

const express = require('express');
const app = express();

let aList;
let bList;
let cList;

module.exports.app = app;
module.exports.aList = aList;
module.exports.bList = bList;
module.exports.cList = cList;
  • ...but i would not put express in data.js , rather put it in app.js . ...但是我不会将express放在data.js ,而是将其放在app.js
  • I would also initialize those vars with initial values in data.js , if the initial data does not depend on something else. 如果初始数据不依赖于其他内容,我也将使用data.js初始值来初始化这些变量。
  • Last but not least: Do not use var anymore, use let and const instead. 最后但并非最不重要的一点:不要再使用var ,而应使用letconst It is supported since Node 6+ ( https://node.green/ ). 自节点6+( https://node.green/ )开始受支持。 I replaced it in the code. 我在代码中替换了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM