Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Zach Kauffman Avatar asked Feb 27 '15 19:02

Zach Kauffman


People also ask

What can you export with Module exports in node JS?

Module exports are the instruction that tells Node. js which bits of code (functions, objects, strings, etc.) to “export” from a given file so other files are allowed to access the exported code.

What does module exports do in node JS?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.

What can you export with module exports?

By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.

How do you declare a static variable in node JS?

Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable. We can use the static variable anywhere.


1 Answers

Your hashtable might be in the wrong scope - it's possibly being clobbered with each 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;
like image 154
floatingLomas Avatar answered Sep 27 '22 20:09

floatingLomas