Reputation: 285
I am currently learning node.js using udemy and I'm having an issue that I absolutely don't understand because it shouldn't be happening.
So the lecture is about accessing external files using node.js with module.exports. I followed exactly the video and it was not working.
here is the code of app.js
require('./utils.js')
console.log(name);
and here is utils.js
const name = 'test' ;
module.exports = name;
Dead simple right ? But it wasn't working. I would get this error :
iMac-de-user:notes-app user$ node app.js
utils.js
/Users/user/Desktop/notes-app/app.js:3
console.log(name)
^
ReferenceError: name is not defined
at Object.<anonymous> (/Users/user/Desktop/notes-app/app.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
iMac-de-user:notes-app user$
So app.js couldn't access the constant name from utils.js (even though my code was exactly the same than the one on the video at this point.) So I downloaded the finished project from the ressources and it was pretty much the same except it was a function that was being exported.
const getNotes = function () {
return 'Your notes...'
}
module.exports = getNotes
I tried it and it worked. So at first I thought that maybe it could access functions and not variables ? It was weird because the trainer did it but that was the only explanation. So I kept it and deleted the function to just add a console.log
const getNotes = console.log('test');
module.exports = getNotes
It worked. At that point I was weirded out because it was pretty much my first code. So i tried changing the names to name again (of course I changed it in the console.log() in app.js as well) and it didnt work. I checked if maybe it was a reserved keyword ? nope. I tried test testTest Name Name1 nameName. Nothing works, nothing except getNotes(everytime I would change the name in app.js and utils.js so a total a 3 constant names changed.)
I don't understand, to the best of my knowledge this is not possible and doesn't make any sense
What's going on ? Is my computer haunted ? It's probably something very stupid but I can't figure it out. I understand it might be a bit confusing so I included 2 pictures.
Thank you for your time.
Upvotes: 1
Views: 400
Reputation: 1
Do something like below you have to store the object or variable exported in a new variable after requiring
it .Make sure you give the correct path in require
statement.
const name=require('./utils.js')
console.log(name);
Exporting it
const name = 'test' ;
module.exports = name;
Also see here
Upvotes: 1