user2704291 user2704291 - 1 year ago 43
Javascript Question

Getting a 'random' value from a module in node.js

Let's say I have a file that looks like this:

var random_nr = Math.floor(Math.random()*array.length);
var x = array[random_nr];
// do some things

exports.random_array_member = x


Now, if I 'require' this in another file, I will always get the same result as long as I don't restart my server, presumably because of caching?

What is the best way to run this code and get a random value, while not including the code into my main file?

Answer Source

The code you have shown is only executed once. The result from that code is then stored as a variable, ready to be exported to whatever file needs it.

Instead, you need to "call" the code at the moment you need a random variable:

exports.random_array_member = function(){
    var random_nr = Math.floor(Math.random()*array.length);
    return array[random_nr];
}

Now, instead of accessing exports.random_array_member, you call exports.random_array_member() in your other files.