简体   繁体   English

JavaScript将数组从一个文件导出到另一个文件以供使用。 Node.js的

[英]JavaScript export array from one file to another to be used. Node.js

Perhaps you can help. 也许你可以帮忙。 I have a file the is listing the DIR then pushing it to an array. 我有一个文件,其中列出了DIR,然后将其推入数组。 I'm then trying to export it and use it in another file. 然后,我尝试导出它并在另一个文件中使用它。 But its not working.... 但是它不起作用....

File 1.js 文件1.js

const fs = require('fs');
let filename = [];
module.exports = function(){


try {
    let subfolder = './DIR/';
    fs.readdir(subfolder, async (err, files) => {
        for (const file of files) {
            filename.push(file);
        }

    });
}
catch (e) {}
};

File 2.js 文件2.js

let instance = require('../../File 2');
console.log(instance);

However when I run this I get an empty array back. 但是,当我运行它时,我得到一个空数组。 however I can console.log within the file 1.js for the array and it shows correctly. 但是我可以在文件1.js中的console.log数组,它可以正确显示。 Not sure what I'm doing wrong. 不知道我在做什么错。

  1. You're exporting a function, not an array. 您要导出的是函数,而不是数组。
  2. The array will be filled asynchronously. 该数组将异步填充。 When you console.log in File 2.js , the array will still be empty. 当您在File 2.js console.log时,该数组仍然为空。

Result was changing File 1.js to be the following: 结果是将文件1.js更改为以下内容:

const fs = require('fs');

module.exports = 
{
    getRArray: function ()
    {
        let filename = [];
        try
        {
            let subfolder = './DIR/';
            let files = fs.readdirSync(subfolder);

            for (let file of files)
            {
                filename.push(file);
            }
        }
        catch (e)
        {
        }
        return filename;
    }
};

with File 2.js 文件2.js

let instance = require('../../DIR');
console.log(instance.getRArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM