3

I have a file which contains code to iterate over a very large array. I'd rather not have the array in the same file as the code to keep things clean. However, I'm not sure how to include the file which contains my array and properly access the individual elements for my iteration. I'd rather not use a JSON object because I don't need key -> value.

  • Use `require` and just return the array from the file – adeneo Apr 20 '14 at 17:00
  • indeed `export` your large array, and `require` it where you need it. See: http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it. And the offical docs: http://nodejs.org/api/modules.html#modules_module_exports – Geert-Jan Apr 20 '14 at 17:02

2 Answers2

4

Either use a regular JavaScript file:

module.exports = [1, 2, 3]

Or a JSON file, which can also be a simple Array:

[1, 2, 3]

Then include it using require:

var arr = require('./array.js'); // Or './array.json'

for(var i = 0; i < arr.length; i++) {
    // arr[i] ...
}
jgillich
  • 71,459
  • 6
  • 57
  • 85
2

Like everyone else is saying, you can use require and put the function into the exports:

myOtherFile.js

exports.largeArrayFunction = function() {
     //do stuff
     return stuff;
}

myMainNodeFile.js

var otherFile = require("myOtherFile.js");
var myArray = otherFile.largeArrayFunction();
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Awesome, this worked. Brought a new issue with the `http` module, but at least I'm going forward. Thanks. –  Apr 20 '14 at 17:19