Here is the error:
logPunishment(target.id, logObj)
^
TypeError: logPunishment is not a function
Code: bot/components/ban.js
const { logPunishment } = require('../db.js')
logPunishment(input1, input2)
some code of: bot/db.js:
async function logPunishment(userId, punishmentObject){
data = await User.findOne({id: userId})
if (!data){
await User.create({id: userId, punishments: []})
data = await User.findOne({id: userId})
}
punishments = data.punishments
punishments.push(punishmentObject)
User.updateOne({id: userId, punishments: punishments})
}
module.exports.logPunishment = logPunishment
logPunishment is clearly a function, but why does it say its not a function? After console.log(logPunishment) this is the result:
undefined
why is that I couldn't understand. Please help! What can I do to fix it now? There are no other errors(for now) apart this Please someone help!!! I have tried this as per a answer
const logPunishment = require('../db.js').logPunishment,
which didn't work Also I'm getting this warning after running the program:
(node:40712) Warning: Accessing non-existent property 'logPunishment' of module exports inside circular dependency
I m not overiding any exports, I have confirmed it.
CodePudding user response:
TL;DR it's because of your circular dependency. Consider the following two files in the same directory:
a.js
const { b } = require('./b');
module.exports.a = 'hello world';
console.log(b());
and b.js
const { a } = require('./a.js');
function b() {
return a;
}
module.exports.b = b;
If you run node a.js
you'll see the circular dependency error
(node:9235) Warning: Accessing non-existent property 'a' of module exports inside circular dependency
If you run node b.js
you'll see
TypeError: b is not a function
This has to do with how require
s get resolved when there are circular dependencies. If you run a
then it requires b
which requires a
which means b
gets a
's unfinished exports, so you'll see undefined
print instead of hello world. If you run b
you'll get b
's unfinished exports in a
which means that you'll be calling undefined
as a function
You can fix it by moving the things that b
requires from a
into a different file: there's not really a good reason to use circular dependencies.