我有一个变量,我想在模块之间共享它并添加到它,从中删除并在Node.js程序中修改它就是我做的:
shared_storage.js
var locations = {};
locations['Brandenburg Gate'] = {latitude: 52.516272, longitude: 13.377722};
locations['Dortmund U-Tower'] = {latitude: 51.515, longitude: 7.453619};
module.exports = locations;
var state = new Object(); // Create the object
state.ready = "r";
state.offline = "o";
state.loaded = "l";
var location_stats = {};
location_stats ['Brandenburg Gate'] = state.ready;
location_stats ['Dortmund U-Tower'] = state.loaded;
module.exports = location_stats ;
mymodule.js
var spots= require('./shared_storage').locations;
console.log(spots);
但结果是:
未定义
我添加到shared_storage.js
?
答案 0 :(得分:1)
更改此
var spots= require('./shared_storage').locations;
this
var spots= require('./shared_storage')
原因是您将对象导出为模块,因此您不需要访问modules属性,因为它没有任何拥有属性:)
现在已修复,您需要重新考虑您的实施。通过另一个模块跨模块共享状态很简单但不好。有几个原因:
更好,最简单的方法是将这些存储在数据库中