A module groups related code into one single, separate unit of code. This can also be seen as moving related functions into a separate file by creating a module. Both the module.exports property and the exports object allow a module to choose what to share with the application.
module.exports and exports
First, exports is the recommended object unless you are planning to change the object type of your module from the traditional ‘module instance’ to something else. If a developer chooses to divide a program into multiple files, this is where module.exports comes in handy to publish variables and functions to the consumer of a model.
It’s the module that returns module.exports to the caller, not exports. The truth is that module.exports does all the heavy lifting and exports is just there to assist module.exports. What exports real job is is collecting properties and attaching them to module.exports, but only if module.exports doesn’t carry something attached already. If there happens to be something already attached to module.exports already, then everything on exports will be ignored.
What module.exports does
Essentially, module.exports is the result of a require call, the object that is returned. Look at the required files as functions that return a single object and you can add properties such as arrays, functions, strings and anything else, to the object by simply setting them on exports. Sometimes we may want the object returned from a require call to be a function that can be called and not just an object with properties.
There are many details to be taken into account when dealing with modules.export and this isn’t necessarily the simplest of models used in Node. Just one interesting thing to mention is that the names added to exports objects don’t not have to be identical at all to the internally scoped name of the model for the particular value being added.
[vc_row][vc_column][td_block_21 separator=”” tag_slug=”node-js” limit=”40″ tdc_css=””][/vc_column][/vc_row]