In Node.js, all variables, functions, classes are visible to each other only within the same file. We are able to call functions from any other file. To do this, we will use require
and module.exports
.
First, create 2 files with which we work, server.js
and index.js
.
In server.js
we just include index.js
And all functions we will write in our index.js
file
Lets add to index.js
object which will contain all of our functions
And add some functions
or
In order that we can use these functions in other files (in our example is server.js
), we need to add at the end of index.js
following code
module.exports is a Node.js specific feature, it does not work with regular JavaScript
If you type in your server.js
file
you will see a similar message in the console
Now let’s use this functions. In server.js
file, write a code that call the functions which we created above
In your terminal you should see the following
Note:
Instead of exports.data = methods;
can be used module.exports = methods;
. In this case, to call the functions, you should use
instead of
Consider another example:
When you connect the module using the require, in fact it will be the function that will allow you to do the following
What is a simplified recording the following code