Usage of module.exports in Node.js

Hello programmers. In this article, you will learn about the purpose and usage of module.exports in Node.js.

module.exports is actually a property of the module object. It helps to achieve modularity in our code. I will explain the concept of modularity in code in a bit. First, let’s get to know more about module object. If you run “console.log(module)” in the terminal in a Node.js app. You will see something like this –

Module {
  id: '.',
  path: 'C:\\Users\\sidsa\\OneDrive\\Desktop\\web dev',
  exports: {},
  filename: 'C:\\Users\\sidsa\\OneDrive\\Desktop\\web dev\\script.js',
  loaded: false,
  children: [],
  paths: [
    'C:\\Users\\sidsa\\OneDrive\\Desktop\\web dev\\node_modules',
    'C:\\Users\\sidsa\\OneDrive\\Desktop\\node_modules',
    'C:\\Users\\sidsa\\OneDrive\\node_modules',
    'C:\\Users\\sidsa\\node_modules',
    'C:\\Users\\node_modules',
    'C:\\node_modules'
  ]
}

Here in the code, you can see exports object which is currently empty. You can attach any function, strings, or object to module.exports object and then use it elsewhere in your another javascript file.

Now, what I mean by modularity is that suppose you are working on a Node.js app that has lots and lots of pieces of code doing different tasks. If someone is assigned to work on the same codebase they will have a hard time knowing what each piece of code does. So we can separate codes that do individual things in a separate file and import them into the main file whenever needed. By this it will be easy for developers to keep track of each piece of code. This helps in achieving abstraction in our code.

Here is an example of using module.exports

module.exports = function fun() {
  return "This is an exported piece of code";
};

Now to use this exported function in another file we will be requiring this code in the same. For this the syntax goes like this –

const imported = require("./script");
imported();

There is one thing to note here is that you can name the imported module file anything you want.

You may also learn,

Leave a Reply

Your email address will not be published.