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
-
exportsis just a shortcut tomodule.exports. - Adding properties is fine.
- Reassigning
exportsbreaks 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
Top comments (0)