node.js - 导出模块而不命名它

标签 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;

或者模块应该导出一个 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/

相关文章:

node.js - nginx 配置 - 将 http 转发到 https,将 www.domain.tld 转发到 domain.tld 和两个子域

node.js - Express - 创建一个新的 View 引擎

javascript - 如何在 forEach 循环中使用 Puppeteer 的 page.click ?

javascript - Node.js 和 Socket.IO - 房间问题

node.js - 使用 puppeteer 循环遍历表格行

javascript - 不允许在本地 Nodejs 服务器中进行跨域请求

node.js - express 虚拟主机 + https

node.js - nodejs + vmware vsphere sdk SOAP 连接

mysql - 使用 SailsJS 在 MySQL 数据库表中设置索引的最佳方法是什么?

node.js - 图像没有方法 'getContext'