我有一个配置文件,其文件格式如下:
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 值?
我不知道我是否理解正确,但是你没有获取数据的主要问题是因为你需要调用函数define(),以便返回你需要的数据,更好的方法是如果你愿意改变你的配置,那么你就这样吧
productItems: {
item1: ['Apple', 'Ball', 'Car'],
item2: ['Dog', 'Elephant', 'Frog'],
item3: ['Goat', 'Hotel', 'Indian']
},