Tuesday, 8 May 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...