How module.exports works in Node.js?

We can use a require call to import another module. So when we require a module, the object that gets returned is the module.exports

For example, when we create a module named hello.js

===============================

exports.sayHello = function() {

return “HELLO”;

};

exports.sayHi = function() {

return “Hi”;

};

================================

Now In order to use the above module, we can call it like this:

var hello = require(“./hello.js”);

Now we can use it like this.

greetings.sayHello ();

greetings.sayHi();

================================

In case if you were thinking what will happen when we add “module.exports = “Hello”;” to the end of our hello.js file.

===============================

exports.sayHello = function() {

return “HELLO”;

};

exports.sayHi = function() {

return “Hi”;

};

module.exports = “Hello”;

================================

When we call greetings.sayHello (); then you will get the error below:

================================

TypeError: object Hello has no

* method ‘sayHello ‘

================================

So what really happened here is that when we added the line module.exports = “Hello”; we basically override everything that was previously assigned to module.exports. So now module.exports is now just a string. It has no method named sayHello.

We hope, you understood how module.exports works and what you need to do when you encounter an error while accessing a method that you have defined.

Like what you read? Give 76 Degrees East Technologies a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.