Today we're going to learn about require
and module
We use require to call some other file and we pass different things from that file using module.
Now we are starting with creating two files app.js
and song.js
. You can create your files as your desired name.
First we’ll write some codes in song.js
file
I know what you are thinking why there is a extra line module.exports
in the end of this file ?
This module.exports
will available this function sing to everyone who required it. So how to require ?
You can just start require by writing require(‘./song)
it will automatically understand it is a js file
Now you can call the sing file by require it and store it in a variable
Now you can call the function from the app.js
file (Sorry I made a mistake there will be Song()
not song()
)
You can run the file now by command node app.js
Final result (Sorry I made a mistake there will be Song()
not song()
)
Do you understand why we use require
and module
now ?
You can see the graphical version here
Originally it published on nerdjfpbblog. You can connect with me in twitter or linkedin !