[英]Node.js - Module exports static variable
I'm attempting to export a module that should store a hashtable of given information so that another call to access that information can be checked for existence in the hashtable, and if found, return the value in the hashtable. 我正在尝试导出一个模块,该模块应该存储给定信息的哈希表,以便可以检查另一个访问该信息的调用是否存在于哈希表中,如果找到,则返回哈希表中的值。
I am having trouble getting the hashtable in the export to remain consistent throughout the app as a singleton/static/global variable. 我无法在导出中获取哈希表以在整个应用程序中保持一致,作为单例/静态/全局变量。
Here's what I have: 这就是我所拥有的:
var Randomize = {
hashTable: [],
randomize: function(rows) {
var randomized = [];
for(var i in rows) {
//check if exists in hashtable, use values accordingly
}
return randomized;
}
};
module.exports = Randomize;
And when I try to access it with: 当我尝试访问它时:
var randomize = require('randomize');
/* ... */
console.log(randomize.randomize(rows))
It creates a new hashtable for each instance. 它为每个实例创建一个新的哈希表。 How can I make it so that it reuses the same instance of hashtable?
我怎样才能使它重用哈希表的相同实例?
Your hashtable might be in the wrong scope - it's possibly being clobbered with each require
. 您的哈希表可能在错误的范围内 - 它可能会被每个
require
所破坏。 Try this instead: 试试这个:
var hashTable = [];
var Randomize = {
hashTable: hashTable,
randomize: function(rows) {
var randomized = [];
for(var i in rows) {
//check if exists in hashtable, use values accordingly
}
return randomized;
}
};
module.exports = Randomize;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.