I am trying to require a file and afterwards pass it to a var. I am following this tutorial to create a authentication system. After writing the server.js file and trying to
I've faced to something like this too. in your routes file , export the function as an object like this :
module.exports = {
hbd: handlebar
}
and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!
For me, when I do Immediately invoked function, I need to put ;
at the end of require()
.
Error:
const fs = require('fs')
(() => {
console.log('wow')
})()
Good:
const fs = require('fs');
(() => {
console.log('wow')
})()
Just wrap in Arrow function where you requiring the files
Remember to export your routes.js
.
In routes.js
, write your routes and all your code in this function module:
exports = function(app, passport) {
/* write here your code */
}
For me, this was an issue with cyclic dependencies.
IOW, module A required module B, and module B required module A.
So in module B, require('./A')
is an empty object rather than a function.
How to deal with cyclic dependencies in Node.js
For me, I got similar error when switched between branches - one used newer ("typescriptish") version of @google-cloud/datastore
packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports
value. I got the error because node_modules still had newer modules used by branch I switched from.