Reputation: 167
I just started to learn NodeJS and ran into a problem while learning modules.
I have 2 files place in the same directory, the first is app.js
and the second is hello.js
.
In the app.js
I wrote :
const hello = require('./hello');
console.log(me);
In the second file, the hello.js
file, I created an object and then exported it using module.exports
:
let me = {
name : 'Bao Chan',
age : 20,
job : 'Developer',
hobbies : ['Listen music', 'Play Videogames']
}
module.exports = me;
Then I saved 2 files and typed node app.js
in the cmd but an error appeared :
ReferenceError: me is not defined
at Object.<anonymous> (E:\Web Dev Assets\Projects\nodejs-tut\app.js:2:13)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
I've been stucking here for like an hour and still haven't figured it out, I don't know if I've missed installing anything or anything's wrong with my code, please help me, thank you guys so much.
Upvotes: 1
Views: 339
Reputation: 669
Call it hello.me
const hello = require('./hello');
console.log(hello .me);
Upvotes: 0
Reputation: 2649
Try this :
hello.js
let me = {
name : 'Bao Chan',
age : 20,
job : 'Developer',
hobbies : ['Listen music', 'Play Videogames']
}
module.exports = {
me: me
};
app.js
const hello = require('./hello');
console.log(hello.me);
Upvotes: 2
Reputation: 1381
just change the variable name hello
to me
const me = require('./hello');
console.log(me);
Upvotes: 0
Reputation: 9648
You're requiring the hello file in a variable called hello
not me
(even though me
is what you actually called the object in the hello.js
file. Try console.log(hello)
Upvotes: 0
Reputation: 1455
You need to call me with the const which you have used for importing your file which is hello here
Try console.log(hello,"---")
Upvotes: 0