javascriptarraysnode.js

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.


Solution

  • 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.