无法在javascript中访问全局变量

时间:2017-10-17 03:38:44

标签: javascript node.js

您好我想在两个java脚本文件中共享一个全局变量,我知道如果我将变量定义为全局变量我应该能够跨java脚本文件访问它。但就我而言,它并没有奏效。我无法弄清楚为什么,我想在first.js文件中共享messages变量以便在second.js文件中访问。当我尝试访问它时,它显示错误,因为未定义消息。有什么建议?

// first.js

let express = require('express');
let router = express.Router();

let elastic = require('../server');
let esClient = elastic.esClient;
let messages = [];

module.exports = router;

// second.js

let express = require('express');
let router = express.Router();

let elastic = require('../server');
let esClient = elastic.esClient;
let messages2 = [];
let data = new Set();

print();

function print(){
  console.log(messages.length);
}

module.exports = router;

// server.js

let express = require('express');
let app = express();
let bodyParser = require('body-parser');

const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
    host: '127.0.0.1:9200',
    log: 'error'
});

app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

module.exports = {
    elasticsearch,
    esClient
};

app.use(require('./routes/first'));
app.use(require('./routes/second'));

app.listen(63145);

3 个答案:

答案 0 :(得分:0)

您可以在module.exports上将多个对象导出为单个对象...如下所示:

let express = require('express');
let router = express.Router();

let elastic = require('../server');
let esClient = elastic.esClient;
let messages = [];

module.exports = { router: router, messages: messages };

然后在第二个文件中:

let express = require('express');
let router = express.Router();
let {messages} = require('./path/to/first.js');
let elastic = require('../server');
let esClient = elastic.esClient;
let messages2 = [];
let data = new Set();

print();

function print(){
  console.log(messages.length);
}

module.exports = router;

但说实话,我不会这样做。而是将您的消息数组构建在它自己的文件中,您可以显式导出,或者设置为可以通过方法访问数组的类。然后将其导出并在其他文件中使用。

答案 1 :(得分:0)

看起来tvanfosso的答案是:

Global variables in Javascript across multiple files

所以可能会发生两件事之一。您没有按正确的顺序将脚本插入到html元素中,或者它没有被正确引用。

答案 2 :(得分:0)

你可以试试这个。 将属性添加到node.js中可用的全局对象。 它将在您的节点项目中可用 //first.js

let express = require('express');
let router = express.Router();

let elastic = require('../server');
let esClient = elastic.esClient;
global.messages = [];

module.exports = { router: router };

// second.js

let express = require('express');
let router = express.Router();    
let elastic = require('../server');
let esClient = elastic.esClient;
//let messages2 = [];

let data = new Set();

print();

function print(){
  console.log(global.messages.length);
}

module.exports = router;