Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node: import object array from another js file?

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

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

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

require('./data.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?

like image 689
vantage5353 Avatar asked May 27 '14 19:05

vantage5353


People also ask

How do I import an array into node js?

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. If you require a module (for the first time), its code is executed and the exports object is returned and cached.

Can I use import in node?

Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.

Can I use both import and require in node JS?

Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice.


2 Answers

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

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

[Edit]

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);};

and calling code:

var mod = require("./mymodule");
mod.push2arr(2);
mod.push2arr(3);
console.log(mod.arr); //output: [2,3]
like image 170
muffel Avatar answered Oct 12 '22 01:10

muffel


I know how to export functions, [...]

An array, or really any value, can be exported the same as functions, by modifying module.exports or exports:

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

exports.arr = arr;
var arr = require('./data').arr;
like image 38
Jonathan Lonowski Avatar answered Oct 12 '22 02:10

Jonathan Lonowski