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

读取properties文件转JS对象时特殊字符转义异常及取值问题求解

解决方案

方案1:使用properties包同步读取(最简便)

properties包本身提供同步解析能力,无需使用回调,可直接返回解析完成的JS对象,完全适配你带Unicode转义的.properties文件格式:

const prop = require("properties");
// 同步读取解析,直接返回结果对象
const properties = prop.parse("./Language_sv.properties", { path: true });
console.log(properties);
// 输出符合预期:{ 'calendar-event-group-configuration': 'Konfigurationsgrupp för evenemang' }

方案2:异步读取封装为Promise(适合异步业务场景)

如果需要保留异步读取逻辑,可以把回调封装为Promise,即可在函数外部正常使用解析结果:

const prop = require("properties");

// 封装为Promise工具函数
function loadProperties(filePath) {
  return new Promise((resolve, reject) => {
    prop.parse(filePath, { path: true }, (error, obj) => {
      if (error) return reject(error);
      resolve(obj);
    });
  });
}

// 调用方式1:async/await (可在任意异步逻辑中使用)
async function initConfig() {
  const properties = await loadProperties("./Language_sv.properties");
  // 此处可正常使用解析后的配置对象
  console.log(properties);
}
initConfig();

// 调用方式2:then回调
loadProperties("./Language_sv.properties")
  .then(properties => console.log(properties))
  .catch(err => console.error("配置读取失败:", err));

方案3:修复properties-reader的转义问题(不想换包时使用)

如果要继续使用原有properties-reader包,可以手动处理多余的转义斜杠,还原Unicode字符:

const PropertiesReader = require("properties-reader");
const properties = PropertiesReader("./Language_sv.properties").getAllProperties();

// 遍历处理所有属性值的转义
for (const key in properties) {
  if (Object.prototype.hasOwnProperty.call(properties, key)) {
    properties[key] = properties[key].replace(/\\u([0-9a-fA-F]{4})/g, (_, code) => {
      return String.fromCharCode(parseInt(code, 16));
    });
  }
}

console.log(properties);
// 输出符合预期

内容的提问来源于stack exchange,提问作者Pascal Sys

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:15:02