What you Export and Import using the Module Object in NodeJs

Module Object and What are Node Modules?

In NodeJs we have often used modules. A module is a global object that is accessible in any NodeJs file. Node Modules are simple or complex reusable codes which you can create by yourself, use in-built ones provided by NodeJs (eg. fs, path, os, etc.), or external ones you download using NPM or Yarn (eg. expressJs, mongoose, luna).


Module Obect

The module object is a special object which you might not be aware you use whenever you import or export files as modules in your project. Take a look at the code below.

export1 code.png The result of the code above will be:

export1 result.jpg

From the image above we can see that the module object contains the "exports" property which in itself is an object that contains what values we are exporting.

Please Note: Don't forget that the exports property of the module object is an object. This is because it is actually this exports(module.exports) object values we will be importing in other codes.

Exporting and importing Modules

Now our previous code could also be written thus:

export 1 second code.png

So we do not need to specify module.exports because the "module" is accessible globally. You can imagine it as the window object which has methods and properties like window.console.log() which could be called on their own like console.log(). Now let's import this module:

import 1 code.png

From the image above: we imported the export1.js file. Now as we have seen, what we exported from export1.js file and imported into the import1.js file is an object("module.exports" or just "exports") which contains the first and second functions as values.

The result of the code above will be:

carbon (4).png

Exporting Other values, in this case, an Array

export 2 code.png \ Importing this we will have: \

carbon (2).png

And when the code is run our output will be:

carbon (3).png

This means that the animals array is a property of the exported animal array present in the exports property of the module object.

Do Names Matter when Importing and Exporting?

Yes, names matter. Make sure you import with the same name you used when exporting.

Conclusion

In conclusion, we have looked at the module global object. We learnt it contains the exports property which includes all the values such as functions, arrays, etc that we want to export as a module.

Thanks for your time!