我正在尝试在nodejs中创建一个翻译模块,将xml文件转换为js对象。
这是我的 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<translation>
<title>This is a title</title>
</translation>
这是我的模块:
const xmlJS = require('xml-js');
const fs = require('fs');
let translation = '';
// convert xml to json to js object
fs.readFile( './translation.xml', function(err, data) {
if (err) throw err;
let convert = xmlJS.xml2json(data, {compact: true, spaces: 2});
let parse = JSON.parse(convert).translation;
translation = parse.en;
});
// wait until export, i have to do this cuz converting xml take like 1sec on my computer,
// so if i'm not waiting before the export my module will return me a blank object.
function canIExport() {
if (translation === '') {
setTimeout(() => {
canIExport();
}, 500);
} else {
exports.translation = translation;
}
}
canIExport();
在我的 app.js 中:
const translation = require('./translation');
这是我的问题,当我尝试调用 translation
对象中的一些文本时
我必须做类似的事情:translation.translation.title._text
。
我必须执行 translation.translation
因为我的 exports.translation = Translation
将我的 var 放入翻译的子对象中(有点像 Inception 中的那样)。
那么如何避免这种情况并只执行类似 translation.title._text
的操作?
最佳答案
这是 XY 问题。导出对象的异步修改是一种反模式。这将导致竞争条件。
模块导出应该完全同步:
const fs = require('fs');
const data = fs.readFileSync( './translation.xml');
...
module.exports = translation;
或者模块应该导出一个 promise :
const fs = require('fs').promises;
module.exports = fs.readFile( './translation.xml')
.then(data => ...);
并按如下方式使用:
const translationPromise = require('./translation');
translationPromise.then(translation => ...);
关于node.js - 导出模块而不命名它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54074084/