21
loading...
This website collects cookies to deliver better user experience
function drinkTea() {
console.log("Mmm, delicious.");
}
drinkTea()
to enjoy a warm beverage. To create a module however, we simply place this function within its own file and tell Node about any functions we wish callers of the module to access.drink.js
with the following contents:function drinkTea() {
console.log("Mmm, delicious.");
}
module.exports.drinkTea = drinkTea;
module.exports
statement to the end of the file. This statement tells Node what methods to export from the module.var drinker = require('./drink');
drinker.drinkTea();
Tea
object and export it from a Node module using the following code:var Tea = function(blend) {
this.blend=blend;
var that = this;
return {
drink: function() {
console.log('Mmm, '+ that.blend+ ', delicious.');
}
};
}
module.exports = Tea;
main
module using code such as:var Tea = require('./drink');
var cupOfTea = new Tea('Assam');
cupOfTea.drink();
>node main
Mmm, Assam, delicious
module.exports.drinkTea = drinkTea
). In the second example, we exported the object without any wrapper (module.exports = Tea
). This allows us to directly create an instance of the module's Tea
object, i.e. we can call new Tea...
rather than new tea.Tea...
21