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?
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.
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.
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.
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]
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With