Understanding module.exports and exports in Node.js

Mar 05, 2019

Before getting started, I would like to tell you all that it is my first blog and I am here to share my understanding on the topic.

Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Node.js is a JavaScript tool that allows developers to write backend (server-side) programs in JavaScript.

What is a module?

A module can be understood as a set of units that can be used to construct a  structure.When creating a module, this can be interpreted as moving all related functions into a file. Let's illustrate this by a example having a file greeting containing two functions:

//greeting.js
sayHelloInEnglish = function() {
  return "Hello";
};

sayHelloInSpanish = function() {
  return "Hola";
};

Exporting a module.

As export  means sending goods to other countries , here it means usage of greeting.js in other files. Lets understand it by 3 step process:

1.The first line of code in greetings.js:

// greetings.js
var exports = module.exports = {};

2.Assign any expression in greetings.js that we want to become available in other files to the exports object:

// greetings.js
// var exports = module.exports = {};

exports.sayHelloInEnglish = function() {
  return "HELLO";
};

exports.sayHelloInSpanish = function() {
  return "Hola";
};

3.Current value of module.exports:

module.exports = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },

sayHelloInSpanish: function() {
    return "Hola";
  }
};

Importing a Module.

Let’s import the publicly available methods of greetings.js to a new file called main.jsin three steps:

1.To import modules the keyword 'require' is always used in node.js:

var require = function(path) {

// ...

return module.exports;
};

2. Requiring greetings.js in main.js:

// main.js
var greetings = require("./greetings.js");

The above code are equivalent to this:

// main.js
var greetings = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },

sayHelloInSpanish: function() {
    return "Hola";
  }
};

3.We can now access the publicly available methods of greetings.js as a property of our greetings variable in main.js.

// main.js
var greetings = require("./greetings.js");

// "Hello"
greetings.sayHelloInEnglish();

// "Hola" 
greetings.sayHelloInSpanish();

Conclusion

Module.exports is the object reference that gets returned from the require() calls. It is automatically created by Node.js. It is also empty by default.

Exports is just a convenience variable so module authors can write less code.Working with its properties is safe and recommended. this

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.