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
I know how to export functions, [...]
An array, or really any value, can be exported the same as function
s, by modifying module.exports
or exports
:
var arr = [ {prop1: value, prop2: value},...];
exports.arr = arr;
var arr = require('./data').arr;
We can use destructuring to solve your problem.
In file1.js, we create an object array:
var arr = [{ prop1: "beep", prop2: "boop" }];
Then we do the following to export:
module.exports = { arr };
Then in another file, file2.js, we require the array from file1
const f1 = require("./file1");
Log the result to test
console.log(f1.arr);
You can simply wrap your array in a function.
// myArray.js
export default function iDoReturnAnArray() {
return ['foo', 'bar', 'baz'];
}
// main.js
import iDoReturnAnArray from './path/to/myArray';
const unwrappedArray = iDoReturnAnArray();
console.log(unwrappedArray); // ['foo', 'bar', 'baz']
You can directly get JSON or JSON array from any file in NODEJS there is no need to export it from a JS script
[ {
prop1: value,
prop2: value
},
{
prop1: val,
prop2: val2
},
...
]
Store it to a JSON file suppose test.json
Now you can export it as given below its very simple.
let data = require('./test.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
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]