Node.js-模块导出静态变量

Node.js - Module exports static variable

本文关键字:静态 变量 js- 模块 Node      更新时间:2024-06-20

我正在尝试导出一个模块,该模块应该存储给定信息的哈希表,以便可以检查访问该信息的另一个调用是否存在于哈希表中,如果找到,则返回哈希表中的值。

我很难将导出中的哈希表作为singleton/static/global变量在整个应用程序中保持一致。

这是我的:

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;

当我尝试使用访问它时

var randomize = require('randomize');
/* ... */
console.log(randomize.randomize(rows))

它为每个实例创建一个新的哈希表。我如何使它重用哈希表的相同实例?

您的哈希表可能在错误的范围内——它可能被每个require所破坏。试试这个:

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;