You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js读取自定义JS配置文件中productItems的子项值?

从AMD格式配置文件中提取productItems的解决方案

现有代码的问题

  1. 未调用函数:你在console.log中传入的是函数本身getProductItems,而非调用函数的结果getProductItems(),因此只会输出函数定义而非目标值。
  2. 正则匹配不可靠:原正则/productItems: {(\s+.+\s+)+}/无法适配JS代码中多变的空格、换行格式,也无法准确捕获完整的对象结构。

解决方案

方案1:通过VM模块执行AMD代码(推荐)

这是最可靠的方式,通过模拟AMD的define函数,执行配置文件代码后直接获取返回的配置对象:

const fs = require('fs');
const vm = require('vm');

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

    // 模拟AMD的define函数,捕获工厂函数返回的配置
    const define = (deps, factory) => {
      config = factory();
    };

    // 在独立沙箱中执行配置文件代码
    vm.runInNewContext(fileData, { define });

    return config.productItems;
  }
};

// 调用函数并打印结果
console.log(getProductItems());

方案2:正则提取并转换为JSON

如果不想执行JS代码,可以提取productItems的内容,修正为合法JSON格式后再解析:

const fs = require('fs');

const getProductItems = () => {
  if (fs.existsSync(configPath)) {
    const fileData = fs.readFileSync(configPath, 'utf8');
    // 匹配productItems对应的对象内容(非贪婪匹配避免捕获过多)
    const match = fileData.match(/productItems:\s*({[\s\S]*?}),/);
    
    if (!match) return null;

    // 修正为合法JSON:单引号转双引号,移除对象/数组末尾的逗号
    const validJson = match[1]
      .replace(/'/g, '"')
      .replace(/,\s*([\]}])/g, '$1');

    return JSON.parse(validJson);
  }
};

console.log(getProductItems());

为什么直接用JSON.parse失败?

原配置文件是AMD模块格式的JS代码,不是纯JSON:

  • 被define([], function(){...})包裹
  • 使用了单引号(JSON要求必须用双引号)
  • 对象最后一个属性末尾有逗号(JSON不允许末尾逗号)

这些语法不符合JSON规范,因此直接JSON.parse会报错。

内容的提问来源于stack exchange,提问作者Arvin Salvador

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:22:37