node.js - 导出未命名的模块
问题描述
我正在尝试在 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;
或者一个模块应该导出一个承诺:
const fs = require('fs').promises;
module.exports = fs.readFile( './translation.xml')
.then(data => ...);
并被这样使用:
const translationPromise = require('./translation');
translationPromise.then(translation => ...);
推荐阅读
- react-native - 不在视野范围内时暂停平面列表中的视频
- sql - 多个原始更新命令的实体框架事务
- spring - 为什么必须对 Spring Boot 应用程序中的用户角色属性进行索引?
- python - 为什么当索引数组为布尔值时,数据框返回一个数值数组?
- ms-access - 打开 Word 文档
- reactjs - 如何在 React 中正确地 fetch() JSON
- java - 使用 while 循环将多个 LinearLayout 添加到滚动视图中
- google-sheets - 如何从包含多个值的单元格中计算一个值?
- zend-framework - zend framework 3 如何在控制器中调用 phtml 文件
- php - 在 Windows 中使用 php 执行 aws cli - 错误未知编码