Node: import object array from another js file?

前端 未结 5 1016
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 14:13

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

相关标签:
5条回答
  • 2021-02-02 14:53

    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;
    
    0 讨论(0)
  • 2021-02-02 14:54

    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);
    
    0 讨论(0)
  • 2021-02-02 15:00

    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']
    
    0 讨论(0)
  • 2021-02-02 15:07

    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');
    
    0 讨论(0)
  • 2021-02-02 15:16

    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]
    
    0 讨论(0)
提交回复
热议问题