Archive for August 14, 2021

module.exports vs exports in Node.js

Posted: August 14, 2021 in Node.js
Tags: ,

Let’s start by developing a simple ( or sample) Node module as shown below.

image

The file mymodule.js contain the following lines of code to expose two functions with the properties a and b using the exports variable.

image

This module is loaded using the require function as shown below.

image

A very simple code with Node.js module and produces the following output.

image

Now, I will change the code in mymodule.js and app.js as follows:

image

image

The program output now changes and properties a and b are no longer available publicly from app.js.

image

So what’s going on in here ? What’s the difference between module.exports and exports ?

module.exports is the variable used by the require function to expose a public property or an API. This variable is actually returned to the calling scope.

The exports variable is just holds a reference to module.exports.

image

So initially they refer to the same object. But if module.exports is directly assigned a value then that value gets returned to the caller’s scope only.

image

The following code will also not work.

image

This will lead to the following error.

image

This is because re-assigning the exports variable to a different object will not have any impact on the contents of the module.exports variable and none of the properties will be publicly exposed to be used by the caller.

This might look a bit confusing. The exports variable is just an alias to expose the public APIs conveniently. If it becomes too much confusing its better to use module.exports.

image