首页 > 解决方案 > 导出未命名的模块

问题描述

我正在尝试在 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呢?

标签: node.js

解决方案


这是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 => ...);

推荐阅读