Understanding module.exports and exports in Node.js
von Satoshi Nakamoto

As builders, we frequently face conditions the place we have to use unfamiliar code. A query will come up throughout these moments. How a lot time ought to I spend money on understanding the code that I am about to make use of? A typical reply is be taught sufficient to begin coding; then discover that matter additional when time permits. Nicely, the time has come to achieve a greater understanding of module.exports and exports in Node.js. This is what I've discovered.
Be aware: this put up covers utilizing modules in Node. If you wish to learn the way you should use modules within the browser, learn: Understanding JavaScript Modules: Bundling & Transpiling.
For a high-quality, in-depth introduction to Node.js, you'll be able to't go previous Canadian full-stack developer Wes Bos. Attempt his course right here, and use the code SITEPOINT to get 25% off and to assist help SitePoint.
What's a Module
A module encapsulates associated code right into a single unit of code. When making a module, this may be interpreted as shifting all associated features right into a file. Let's illustrate this level with an instance involving an utility constructed with Node.js. Think about that we created a file referred to as greetings.js and it comprises the next two features:
// greetings.js
sayHelloInEnglish = perform() {
return "Hi there";
};
sayHelloInSpanish = perform() {
return "Hola";
};
Exporting a Module
The utility of greetings.js will increase when its encapsulated code could be utilized in different information. So let's refactor greetings.js to realize this purpose. To grasp what is definitely taking place, we are able to comply with a three-step course of:
1) Think about that this line of code exists as the primary line of code in greetings.js:
// greetings.js
var exports = module.exports = {};
2) Assign any expression in greetings.js that we need to change into accessible in different information to the exports object:
// greetings.js
// var exports = module.exports = {};
exports.sayHelloInEnglish = perform() {
return "HELLO";
};
exports.sayHelloInSpanish = perform() {
return "Hola";
};
Within the code above, we might have changed exports with module.exports and achieved the identical end result. If this appears complicated, do not forget that exports and module.exports reference the identical object.
3) That is the present worth of module.exports:
module.exports = {
sayHelloInEnglish: perform() {
return "HELLO";
},
sayHelloInSpanish: perform() {
return "Hola";
}
};
The put up Understanding module.exports and exports in Node.js appeared first on SitePoint.
Source link
Read the full article
Satoshi Nakamoto
Keine Verbindung
Verbindung wird wiederhergestellt
Etwas ist schiefgelaufen
Wir sind gleich wieder da