简体   繁体   English

从node.js中的模块获取“随机”值

[英]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? 在不将代码包括到我的主文件中的同时,运行此代码并获取随机值的最佳方法是什么?

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. 现在,不用访问exports.random_array_member ,而是在其他文件中调用exports.random_array_member()

Lets play with getters 让我们与吸气剂一起

random.js random.js

var array = [1, 2, 3, 4, 5];

module.exports = {
  get random_array_member() {
    return array[Math.floor(Math.random()*array.length)]
  }
}

consumer.js Consumer.js

var r = require('./random')

console.log(r.random_array_member)
console.log(r.random_array_member)
console.log(r.random_array_member)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM