最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Include an array from another file (nodejs) - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 20, 2014 at 16:58 user623990user623990 2
  • Use require and just return the array from the file – adeneo Commented Apr 20, 2014 at 17:00
  • indeed export your large array, and require it where you need it. See: stackoverflow./questions/5311334/…. And the offical docs: nodejs/api/modules.html#modules_module_exports – Geert-Jan Commented Apr 20, 2014 at 17:02
Add a ment  | 

2 Answers 2

Reset to default 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] ...
}

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();
发布评论

评论列表(0)

  1. 暂无评论