【问题标题】:Accessing non-existent property of module.exports inside circular dependency NodeJS在循环依赖NodeJS中访问module.exports不存在的属性
【发布时间】:2021-08-01 05:59:42
【问题描述】:

在 NodeJS 中使用 module.exports 时遇到了一些问题,我遵循了多个指南,并且几乎可以肯定我做得对。 我必须编写脚本、main.js 和 event.js。我试图从 main.js 共享一个函数到 event.js,但它不起作用。代码如下:

Main.js

function Scan(){
    if(fs.readdirSync('./events/').length === 0){
        console.log(colors.yellow('Events Folder Empty, Skipping Scan'))
    } else {
        var events = fs.readdirSync('./events/').filter(file => file.endsWith('.json'))
                for(const file of events){
                    let rawdata = fs.readFileSync('./events/' + file);
                    let cJSON = JSON.parse(rawdata);
                }
                events.sort()
                tevent = events[0]
                StartAlerter()
                }
}

module.exports = { Scan };

Event.js

const main = require('../main')

main.Scan;

这会返回错误:

(node:19292) Warning: Accessing non-existent property 'Scan' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)

我做错了什么?

【问题讨论】:

  • 请显示文件系统。进口声明准确吗?
  • Main.js 在 event.js 的父目录下。我不知道导入语句是否准确,因为我不是所有的 js 经验
  • 如果main.js和event.js都在同一个目录下,那么import语句应该是 const main = require('./main') 这样解决了吗?
  • 它们不在同一个目录下,main在event的父目录下
  • 主模块在哪里导入事件模块? 为什么这些会相互导入?

标签: javascript node.js function module.exports


【解决方案1】:

问题解决了,这是我的不同做法:

module.exports = { Scan };

在定义扫描函数之前声明,如下所示:

module.exports = { Scan };
function Scan(){
//Code
}

然后在 event.js 中,我写了

const main = require('../main')

因为它现在是一个模块,并且可以与 require() 函数一起使用。 然后在event.js中执行函数,我写了

main.Scan()

执行它。

【讨论】:

  • 移动module.exports = { Scan }; 不会改变任何东西,function Scan 无论如何都会被提升。
【解决方案2】:

更好的尝试:

module.exports = Scan;

【讨论】:

  • 任何地方都没有解构
  • 是真的,我有混淆的概念,感谢您的观察。
猜你喜欢
  • 2021-02-13
  • 2021-02-19
  • 2022-06-13
  • 2021-05-17
  • 1970-01-01
  • 2021-03-01
  • 2021-03-28
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多