NodeJs:TypeError:require(...)不是函数

问题描述 投票:55回答:4

我试图要求一个文件,然后将其传递给var。我正在关注this教程以创建一个身份验证系统。在编写server.js文件并尝试编译后,我得到了一个bson错误,因此我更改了需要在mongoose中发布版本的行。

这是我的代码和错误:

server.js

    require('./app/routes')(app, passport);

错误

require('./app/routes')(app, passport);
                   ^

TypeError: require(...) is not a function
           at Object.<anonymous> (d:\Node JS learning\WorkWarV2\server.js:38:24)
           at Module._compile (module.js:434:26)
           at Object.Module._extensions..js (module.js:452:10)
           at Module.load (module.js:355:32)
           at Function.Module._load (module.js:310:12)
           at Function.Module.runMain (module.js:475:10)
           at startup (node.js:117:18)
           at node.js:951:3

Process finished with exit code 1

我已经读过,这通常意味着requireJS没有正确加载,但我不知道为什么或如何解决它。

由于评论而编辑:

据问,hereconsole.log(require);的结果

javascript node.js require
4个回答
80
投票

我认为这意味着你的module.exports模块中的./app/routes没有被赋值为函数,因此require('./app/routes')没有解析为函数,因此,你不能将它称为像这样的函数require('./app/routes')(app, passport)

如果您希望我们对此进行进一步评论,请向我们展示./app/routes

看起来应该是这样的;

module.exports = function(app, passport) {
    // code here
}

您正在导出一个可以像require('./app/routes')(app, passport)一样调用的函数。


可能发生类似错误的另一个原因是,如果您有一个循环模块依赖项,其中模块A正在尝试require(B)而模块B正在尝试require(A)。当发生这种情况时,它将被require()子系统检测到,其中一个将作为null返回,因此试图将其称为函数将无效。在这种情况下的修复是删除循环依赖,通常是通过将公共代码分成第三个模块,两个都可以单独加载,虽然修复循环依赖的细节对于每种情况都是唯一的。


13
投票

对我来说,当我立即调用函数时,我需要将;放在require()的末尾。

错误:

const fs = require('fs')

(() => {
  console.log('wow')
})()

好:

const fs = require('fs');

(() => {
  console.log('wow')
})()

10
投票

对我来说,这是一个循环依赖的问题。

IOW,模块A需要模块B,模块B需要模块A.

所以在模块B中,require('./A')是一个空对象而不是一个函数。

How to deal with cyclic dependencies in Node.js


-3
投票

记得出口你的routes.js

routes.js中,在此功能模块中编写您的路线和所有代码:

exports = function(app, passport) {

/* write here your code */ 

}
© www.soinside.com 2019 - 2024. All rights reserved.