DEV Community

Cover image for Day 6 - Require & Module - Learning Node JS In 30 Days [Mini series]
Muhammad Ali (Nerdjfpb)
Muhammad Ali (Nerdjfpb)

Posted on • Edited on • Originally published at blog.nerdjfpb.com

Day 6 - Require & Module - Learning Node JS In 30 Days [Mini series]

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.

Alt Text

First we’ll write some codes in song.js file

Alt Text

I know what you are thinking why there is a extra line module.exports in the end of this file ?

Alt Text

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

Alt Text

Now you can call the function from the app.js file (Sorry I made a mistake there will be Song() not song())

Alt Text

You can run the file now by command node app.js

Alt Text

Final result (Sorry I made a mistake there will be Song() not song())

Alt Text

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 !

Top comments (6)

Collapse
 
everuniverse profile image
everuniverse

In song.js you export sing. In app.js you declare Song and call song(). To me it makes no sense. Running app.js leads to a reference error (in app.js) regarding song. Same error when calling sing().

Collapse
 
nerdjfpb profile image
Muhammad Ali (Nerdjfpb)

Sorry! there will be Song().
I mistakenly wrote song()

Collapse
 
everuniverse profile image
everuniverse

Alright! That works.

Thread Thread
 
nerdjfpb profile image
Muhammad Ali (Nerdjfpb)

Cool then! Happy coding!

Collapse
 
ahmad-ali14 profile image
Ahmad Ali

question: is song() equal to song. sing();?

Collapse
 
nerdjfpb profile image
Muhammad Ali (Nerdjfpb)

Nope they are not the same one.
In song.js file we are sending the sing function as default. So when we call Song() in app.jsthen it is pointing to the sing function.

But if we write Song.sing() then it means we are trying to get sing.sing() function which is not here. This is will an error.

Check dev.to/nerdjfpb/day-7-learning-nod... this one to get the idea how to do song.sing()