[Node.js] Exporting Modules in Node

时间:2024-01-22 09:46:20

In this lesson, you will learn the difference between the exports statement and module.exports. Two examples are demonstrated, each accomplishing the same task but one using export statements and one using module.exports. You will also learn the basic thumb rule to identify which is appropriate for your current needs.

// circle.js using the exports statement
var PI = Math.PI; exports.area = function(r){
return PI * r * r;
} exports.circumference = function(r){
return 2 * Pi * r;
}
// accessing the exported functions in the node shell
var circle = require('./circle.js'); circle.area(4);
circle.circumference(4);

---------------------

// using module.exports to demonstrate the same functionality
var PI = Math.PI; module.exports = function(r){
return {
area: function(){
return PI * r * r;
},
circumference: function(){
return 2 * PI * r;
}
}
}
// accessing the exposed functions in the node shell
var circle = require('./circle.js'); var myCircle = circle(4); myCircle.area();
myCircle.circumference();

To summarize that, the general thumb rule is use the exports statement to export instances of modules. Use the module.exports statement to export JavaScript objects.