Modules are like reusable components that can be used across applications. It’s like encapsulating a functionality in a separate module.

Benefits of modules in node.js:

1.) Code re-usability
2.) By delegating separate functionality to individual modules, code becomes modular.

In node.js modules, we can expose functions and variables to outside world.

Let’s see an example,

Suppose I need to a functionality to convert a given message into a specific format i.e.
Given Message = “Hello”
Converted Message = “[START]Hello[END]”

And then there should be an another functionality to reconvert the message to original format i.e.
Given Message = “[START]Hello[END]”
Converted Message = “Hello”

Now we should delegate this message conversion functionality to a separate module. This module should expose two operations i.e.

1.) Convert Given Message
2.) Reconvert Given Message

Code for message_converter module is as follows,

File Name = message_converter.js

There are 3 functions in above module but only 2 out of them will be visible to outside world, because we have exported only 2 functions by adding them in the exports object.

So, let’s see how to use this module,

It’s output will be,

[Start]Sample String[END]
Sample String

Now how did that worked and what the hell is this exports object?

Actually every module has an object module.exports that is exposed to one who includes this module.
At the start of each module a line is implicitly added i.e.

So, exports is a reference to module.exports. Therefore whatever function we add in exports object gets eventually added to module.exports.

But what if we overwrite exports object ?

Overwriting exports with any other variable will break the link between module.exports and exports. Therefore your module will not be able to expose anything using this overwritten exports object.

Lets understand by an example,

Suppose instead of 2 functions, we want to expose the complete object from the module for conversion and reconversion. Also, start and end tags will be passed from outside.

Code for this module is as follows,

File Name = message_converter_2.js

Here in this module, we exported the complete class using module.exports . It would have not worked with exports object i.e.

Because by reassigning exports object we are not actually adding anything in module.exports object.

Always remember this module.exports is the Big Daddy i.e. it only exposes the object to outside world. exports object is only a reference to it and if you change that reference then you cannot access module.exports through exports keyword.

Now let’s see how to use this module,

So, this is how we our create custom modules in node.js .

Thanks & Happy Coding.