Tuesday, February 27, 2018

javascript - How do I export an array with module.exports in node js?



I have a project using node.js. It's my first time using nodejs and I want to export an array to my app. Here is some code:



module.exports = { 
var arrays = [];
arrays[0] = 'array 0';

arrays[1] = 'array 1';
arrays[2] = 'array 2';
arrays[3] = 'array 3';
arrays[4] = 'array 4';
var r_array = arrays[Math.floor(Math.random() * arrays.length)].toString();
}


At the end I want to use the var r_array in my app.js but I don't know how.


Answer




You'd want to define a function which returns the randomized portion of the array:



module.exports = {
getRArray: function() {
var arrays = [];
arrays[0] = 'array 0';
arrays[1] = 'array 1';
arrays[2] = 'array 2';
arrays[3] = 'array 3';
arrays[4] = 'array 4';

return arrays[Math.floor(Math.random()*arrays.length)];
}
};


Also you should embed the array into the function so it actually returns something.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...