使用nodejs文件系统从自定义js文件返回对象中按键读取数组值

问题描述 投票:0回答:1

我有一个配置文件,其文件格式如下:

    define([], function () {
        return {
            productItems: {
                item1: ['Apple', 'Ball', 'Car'],
                item2: ['Dog', 'Elephant', 'Frog'],
                item3: ['Goat', 'Hotel', 'Indian']
            },
        };
    });

我尝试过 JSON.parse() ,不幸的是它无法读取或无法解析,可能是因为格式错误。

我还使用了文件系统模块,但我无法使用以下代码获得正确的值:

const getProductItems = () => {
      if (fs.existsSync(configPath)) {
        const fileData = fs.readFileSync(configPath, 'utf8');

        const productItems= fileData.match(/productItems: {(\s+.+\s+)+}/);
    
        return productItems;
     }
    }

    console.log(getProductItems);

它只返回函数而不返回值。我如何从这个自定义 js 文件中获取 item1、item2 和 item3 值?

javascript node.js arrays typescript javascript-objects
1个回答
-1
投票

我不知道我是否理解正确,但是你没有获取数据的主要问题是因为你需要调用函数define(),以便返回你需要的数据,更好的方法是如果你愿意改变你的配置,那么你就这样吧

productItems: {
            item1: ['Apple', 'Ball', 'Car'],
            item2: ['Dog', 'Elephant', 'Frog'],
            item3: ['Goat', 'Hotel', 'Indian']
        },
© www.soinside.com 2019 - 2024. All rights reserved.