Node: import an array of objects from another js file?

In a file called data.js, I have a large array of objects:

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

I would like to use this array in my Node.js application, but the code is kind of

 require('./data.js') 

Does not help. I know how to export functions, but I get lost when it comes to “importing” arrays. How to add data.js file to app.js app?

+6
source share
3 answers

Local variables (var any) are not exported and are not local to the module. You can define your array on the export object so that you can import it. You can also create a .json file if your array contains only simple objects.

data.js:

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

import.js

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

[change]

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

However, you can modify objects from the module code. Consider this module:

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

and call code:

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

You can directly get a JSON or JSON array from any file in NODEJS; you don’t need to export it from a JS script

  [ { prop1: value, prop2: value }, { prop1: val, prop2: val2 }, ... ] 

Save it in a JSON file, assume test.json

Now you can export it as shown below, very simply.

 let data = require('./test.json'); 
+1
source

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

An array or indeed any value can be exported in the same way as function s by changing module.exports or exports :

 var arr = [ {prop1: value, prop2: value},...]; exports.arr = arr; 
 var arr = require('./data').arr; 
0
source

Source: https://habr.com/ru/post/969925/


All Articles