What is the difference between module.exports and exports in NodeJS?

Tram Ho


exports and module.exports , not export them. A lot of you often lack the “s”. In Javascript, there is the keyword export but not in NodeJS.

What is the NodeJS Wrapping mechanism?

Before the code in the module is executed, NodeJS will wrap the code as follows:

What is the difference between module.exports and exports?

First, module.exports and exports point to the same Object, which is an empty Object .

However, only one module.exports is actually exported when I require it. The exports guy is not. It is just a reference to module.exports .

Examples are as follows:

The result will be

Here you can see that these two guys just changed the properties of the original Object (the original empty Object). So here, these two guys are still the same Object .

However, if corrected

Two guys are two different object, because he is the guy assign value to exports (I use the =) The result would be

I further proved the following:

In the export.js file export.js wrote

Then, in the index.js file I wrote

The result is {}

Because only module.exports is the guy who is actually exported (And it is an empty Object by default). The exports guy does not.

So when to use exports?

Use exports only if you want to add a property to its default Object. For example instead of writing

It can be written as follows to make it shorter and more convenient.


Always use module.exports when you want to export something. Don’t be afraid to use exports for confusion.

Currently I am learning to write Blog at https://htknguyen.com/ . If you are interested, then visit my blog to hear me slashing the wind up in the perspective of a leprous Developer. Shoot heart

Share the news now

Source : Viblo