As developers, we often face situations where we need to use unfamiliar code. A question will arise during these moments. How much time should I invest in understanding the code that I'm about to use? A typical answer is learn enough to start coding; then explore that topic further when time permits. Well, the time has come to gain a better understanding of module.exports
and exports
in Node.js. Here's what I have learned.
What is a Module
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file. Let's illustrate this point with an example involving an application built with Node.js. Imagine that we created a file called greetings.js
and it contains the following two functions:
Exporting a Module
The utility of greetings.js
increases when its encapsulated code can be utilized in other files. So let's refactor greetings.js
to achieve this goal. To comprehend what is actually happening, we can follow a three-step process:
1) Imagine that this line of code exists as the first line of code in greetings.js
:
2) Assign any expression in greetings.js
that we want to become available in other files to the exports
object:
In the code above, we could have replaced exports
with module.exports
and achieved the same result. If this seems confusing, remember that exports
and module.exports
reference the same object.
3) This is the current value of module.exports:
[js] module.exports = { sayHelloInEnglish: function() { return "HELLO"; }, sayHelloInSpanish: function() { return "Hola"; } }; [/js]Continue reading %Understanding module.exports and exports in Node.js%