DEV Community

๐Ÿš€ Backend Internals #4: exports vs module.exports - What's the Difference?

Most Node.js beginners think these are interchangeable:

exports.sayHi = () => console.log("Hi");
module.exports = () => console.log("Hi");

But there's one important difference that can leave you scratching your head when require() suddenly returns {}.

The hidden truth

When Node.js runs your file, it creates something like this:

(function (exports, require, module) {
  // Your code
});

At the beginning:

exports === module.exports // true

So this works:

exports.add = (a, b) => a + b;

...because you're adding a property to module.exports.

The common mistake

exports = function () {
  console.log("Hello");
};

This doesn't export your function. Why? Because you've only changed the local exports variable. module.exports still points to the original empty object, and that's what require() returns.

Rule to remember

  • โœ… Export multiple values:
    exports.add = add;
    exports.sub = sub;
    
  • โœ… Export one function, class, or object:
    module.exports = MyClass;
    
  • โŒ Never do: exports = MyClass;

๐Ÿ’ก Takeaway

  • exports is just a shortcut to module.exports.
  • Adding properties is fine.
  • Reassigning exports breaks the connection.
  • For single exports, always use module.exports.

Have you ever been confused by require() returning {}? Now you know why.

#NodeJS #JavaScript #Backend #WebDevelopment #Programming

Comments

No comments yet. Start the discussion.