1、propertiesParser.js
let readline = require('readline');
let fs = require('fs');
// properties文件路径
let local = 'zh',
url = local == 'zh' ? /public/messages_zh.properties' : '/public/messages_en.properties';
// Unicode 码转为中文
let toGB2312 = function(str) {
return unescape(str.replace(/\\u/gi, '%u'));
}
// properties文件解析
let parseProps = function() {
let fRead = fs.createReadStream(url),
readlineObj = readline.createInterface({
input: fRead
}); readlineObj.on('line', (line) => {
var tmp = line.toString(),
index = tmp.indexOf('#');
// 拆分key、value
if (index != 0) {
let strIdx = tmp.indexOf('='),
key = tmp.substr(0, strIdx),
value = tmp.substr(strIdx + 1);
// 将拆分key、value数据存储到node的全局变量global下的local属性
global.local[key] = local == 'zh' ? toGB2312(value) : value;
}
})
// 文件读取结束
readlineObj.on('close', () => {
console.log('readline close... parsed properties!');
})
} module.exports = {
parseProps
}
网上也有jquery.i18n.properties等方案,感觉引入过多冗余资源,索性手撸一个纯js方法实现解析,希望也能帮到遇到类似问题的人 ^_^ 。