节点:从另一个js文件导入对象数组? [英] Node: import object array from another js file?

查看:171
本文介绍了节点:从另一个js文件导入对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个名为data.js的文件中,我有一个大对象数组:

In a file called data.js, I have a big object array:

var arr = [ {prop1: value, prop2: value},...]

我想在我的Node.js应用程序中使用此数组,但是代码类似

I'd like to use this array into my Node.js app, but code like

require('./data.js')

没有帮助.我知道如何导出功能 ,但是当涉及到导入" 数组时我迷路了.如何将data.js文件添加到我的app.js中?

doesn't help. I know how to export functions, but I'm lost when it comes to "importing" arrays. How do I add the data.js file to my app.js?

推荐答案

局部变量(无论变量是什么)都不会导出,而是局部于模块.您可以在导出对象上定义数组以允许导入.如果您的数组仅包含简单对象,则也可以创建.json文件.

Local variables (var whatever) are not exported and local to the module. You can define your array on the exports object in order to allow to import it. You could create a .json file as well, if your array only contains simple objects.

data.js:

module.exports = ['foo','bar',3];

import.js

import.js

console.log(require('./data')); //output: [ 'foo', 'bar', 3 ]

(首次需要)模块时,将执行其代码,并返回并缓存 exports 对象.对于require()的所有其他调用,仅返回缓存的上下文.

If you require a module (for the first time), its code is executed and the exports object is returned and cached. For all further calls to require(), only the cached context is returned.

尽管如此,您仍可以在模块代码中修改对象.考虑以下模块:

You can nevertheless modify objects from within a modules code. Consider this module:

module.exports.arr = [];
module.exports.push2arr = function(val){module.exports.arr.push(val);};

和调用代码:

var mod = require("./mymodule");
mod.push2arr(2);
mod.push2arr(3);
console.log(mod.arr); //output: [2,3]

这篇关于节点:从另一个js文件导入对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆