【问题标题】:Is there a way to access module.exports.myInstance in a function from other file?有没有办法从其他文件访问函数中的 module.exports.myInstance?
【发布时间】:2020-08-06 08:36:16
【问题描述】:

我想从其他文件的函数中访问module.exports.myInstance,如下所示。

// a.js
const func = async function () {
  ...
  module.exports.myInstance = ...;
}
func();

// b.js
const module = require("a.js").myInstance;
console.log(module);

我需要将module.exports 放在一个函数中,因为我有一些事情要处理等待获得myInstance。我尝试过并测试过,但是当console.log(module) 时,我得到了undefined。这不是一种可能的格式吗?如果是,我应该怎么做才能完成这项工作?

【问题讨论】:

    标签: node.js async-await module.exports


    【解决方案1】:

    这是一个非常糟糕的模式。要让它发挥作用,你应该写:

    // a.js
    const func = async function () {
      module.exports.myInstance = 'hello'
    }
    func()
    
    // b.js
    require('./a.js') // trigger the async function
    
    // wait the loading with nextTick or setTimeout (if the operation takes longer)
    process.nextTick(() => {
      // you must re-run the require since the first execution returns undefined!
      console.log(require('./asd.js').myInstance)
    })
    

    如你所见,基于时间和执行顺序的这段代码真的很脆弱。

    如果你想要一个单例,你可以这样写:

    // a.js
    let cached
    module.exports = async function () {
      if (cached) {
        return cached
      }
      cached = 'hello'
      return cached
    }
    
    // b.js
    const factory = require('./a.js')
    
    factory()
      .then(salut => { console.log(salut) })
    

    【讨论】:

    • 我想在 b.js 中使用 factory 作为全局实例,类似于 factory.aaa.bbb()factory.ccc.ddd()。但是以你的例子,看起来我必须在then()中使用aaa.bbb()ccc.ddd()
    • 嗯,我已经测试了你给出的第一个例子,它的结果是一样的undefined
    • 我拼错了文件名require('./asd.js')。它适用于节点 12
    • 这对我不起作用。我也在使用节点 12。 myInstance 在我的情况下是 new Class() 在 a.js。这可能是为什么它对我不起作用吗?我很困惑。
    • 要使用nextTick,您需要了解event loop queues 如果您更改示例,您应该使用setTimeout,因为其他代码可能会更改代码的执行顺序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2021-04-03
    • 2023-04-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    相关资源
    最近更新 更多