Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 27171  / 3 Years ago, mon, may 10, 2021, 12:00:00

Im having some issues when using module.exports inside NodeJS, and I've followed multiple guides, and im almost certain Im doing it right.
I have to scripts, main.js and event.js. Im trying to share a function from main.js to event.js, but its not working. Here is the code:


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;

This returns the error:


(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)

What am I doing wrong?


More From » node.js

 Answers
86

Problem solved, heres what I did differently:


module.exports = { Scan };

Is declared before the Scan function is defined, like so:


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

Then in event.js, I wrote


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

As it is now a module, and can be used with the require() function.
Then to execute the funciton in event.js, I write


main.Scan()

To execute it.


[#50293] Sunday, April 11, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mikael

Total Points: 73
Total Questions: 115
Total Answers: 86

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
;