I have a simple class Date with a few functions. One of them is SetMonthAndYear.
I export this class with module.export to make it accessible for other classes:
class MyDateClass {
currentMonth = 0;
currentYear = 0;
async SetMonthAndYear(timeStamp){
var date = new Date(timeStamp);
if(date.getFullYear() != this.currentYear || (date.getMonth() + 1) != this.currentMonth){
this.currentYear = new Date(Date.now()).getFullYear();
this.currentMonth = new Date(Date.now()).getMonth() + 1; // getMonth() gives 1 month earlier for some reason.
console.log("New month and year is set: " + this.currentMonth + " - " + this.currentYear)
return true;
}
return false;
}
}
module.exports = new MyDateClass();
In an other class I request this function to check if the month and year need to be updated like so:
var dateClass = require(./MyDateClass.js);
class OtherClass
{
var currentTimeStamp = ~some timestamp~;
async main(){
if (await dateClass.SetMonthAndYear(currentTimeStamp))
{
console.Log("The month and year are modified");
}
console.Log("Done.");
}
main();
}
Now the weird part: The first run this code sets the month and year and gives this as output (which I expect):
New month and year is set: 1 - 2025
The month and year are modified
Done.
The second run this is the output:
The month and year are modified
Done.
So in the function the if statement is seen as false, but the function seems to be returning true while I expect false as a return value?
I'm new with Nodejs module exports and suspect I'm doing something wrong here, but can't figure out what exactly?
async? Also don't export class instances.class OtherClass, its body contains raw statements. Please provide a minimal reproducible example. Are you sure your actual code contains theawait?Date, it shadows the globalDateobject. You seem to be mixing them up yourself already.