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
var another = require('./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
var methods = {};
And add some functions
var methods = {
timestamp: function() {
console.log('Current Time in Unix Timestamp: ' + Math.floor(Date.now() / 1000));
},
currentDate: function() {
console.log('Current Date is: ' + new Date().toISOString().slice(0, 10));
}
};
or
methods.timestamp = function() {
console.log('Current Time in Unix Timestamp: ' + Math.floor(Date.now() / 1000))
};
methods.currentDate = function() {
console.log('Current Date is: ' + new Date().toISOString().slice(0, 10))
};
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
exports.data = methods;
module.exports is a Node.js specific feature, it does not work with regular JavaScript
If you type in your server.js
file
console.log(another)
you will see a similar message in the console
/user> node server.js
{ data: { timestamp: [Function], currentDate: [Function] } }
Now let’s use this functions. In server.js
file, write a code that call the functions which we created above
another.data.timestamp();
another.data.currentDate();
In your terminal you should see the following
Current Time in Unix Timestamp: 1465804362
Current Date is: 2016-06-13
Note:
Instead of exports.data = methods;
can be used module.exports = methods;
. In this case, to call the functions, you should use
another.timestamp();
another.currentDate();
instead of
another.data.timestamp();
another.data.currentDate();
Consider another example:
var level = function(num) {
return num > 40 ? "It's over 40!" : num;
};
module.exports = level;
When you connect the module using the require, in fact it will be the function that will allow you to do the following
require('./index.js')(50);
What is a simplified recording the following code
var level = require('./index.js')
level(50);