Introducing module.exports | How to export in Node.js

Introducing module.exports | How to export in Node.js

Introduction

Using modules is an essential part of building complete applications and software systems using Node.js. In the absence of modules, your code would be fragmented and difficult to run, let alone maintain over time. But what is a module? And how exactly are you supposed to use module.exports to build your Node.js programs?

A module is a discrete program, contained in a single file in Node.js. Modules are therefore tied to files, with one module per file. Modules are available in other programming languages. Node.JS uses the CommonJS system of modules, but there are other module types used in the JavaScript ecosystem. The most prominent of these other module systems are the Asynchronous Module Definition (AMD) and the (ECMAScript 6) ES6 module systems.

As we will see, module.exports is an object that the current module returns when it is "required" in another program or module.

You can include functionality from other modules in any other module. To do so is referred to as "requiring" the module, which is simply calling for a certain special object representing the functionality of the module.

Requiring a Module

Node.js comes with a set of built-in modules that we can use in our code without having to install them. To do this, we need to require the module using the require keyword and assign the result to a variable. This can then be used to invoke any methods the module exposes.

For example, to list out the contents of a directory, you can use the file system module and its readdir method:

const fs = require('fs');
const folderPath = '/home/jim/Desktop/';

fs.readdir(folderPath, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});

Note that in CommonJS, modules are loaded synchronously and processed in the order they occur.

How to creating and Exporting a Module

Now let’s look at how to create our own module and export it for use elsewhere in our program. Start off by creating a user.js file and adding the following:

const getName = () => {
  return 'Jim';
};

exports.getName = getName;

Now create an index.js file in the same folder and add this:

const user = require('./user');
console.log(`User: ${user.getName()}`);

Run the program using node index.js and you should see the following output to the terminal:

User: Jack

So what has gone on here? Well, if you look at the user.js file, you’ll notice that we’re defining a getName function, then using the exports keyword to make it available for import elsewhere. Then in the index.js file, we’re importing this function and executing it. Also notice that in the require statement, the module name is prefixed with ./, as it’s a local file. Also note that there’s no need to add the file extension.

Exporting Multiple Methods and Values

We can export multiple methods and values in the same way:


const getName = () => {
  return 'Jack';
};

const getLocation = () => {
  return 'Tokyo';
};

const dateOfBirth = '24.09.1984';

exports.getName = getName;
exports.getLocation = getLocation;
exports.dob = dateOfBirth;

And in index.js:

const user = require('./user');
console.log(
  `${user.getName()} lives in ${user.getLocation()} and was born on ${user.dob}.`
);

The code above produces this:

Jack lives in Tokyo and was born on 24.09.1984.

Notice how the name we give the exported dateOfBirth variable can be anything we fancy (dob in this case). It doesn’t have to be the same as the original variable name.

Variations in Syntax

I should also mention that it’s possible to export methods and values as you go, not just at the end of the file.

For example:


exports.getName = () => {
  return 'Jack';
};

exports.getLocation = () => {
  return 'Tokyo';
};

exports.dob = '24.09.1984';

And in index.js:

const { getName, dob } = require('./user');
console.log(
  `${getName()} was born on ${dob}.`
);

As you might expect, this logs:

Jack was born on 24.09.1984.

Exporting a Default Value

In the above example, we’re exporting functions and values individually. This is handy for helper functions that could be needed all over an app, but when you have a module that exports just the one thing, it’s more common to use module.exports:


class User {
  constructor(name, age, email) {
    this.name = name;
    this.age = age;
    this.email = email;
  }

  getUserStats() {
    return `
      Name: ${this.name}
      Age: ${this.age}
      Email: ${this.email}
    `;
  }
}

module.exports = User;

And in index.js:


const User = require('./user');
const jim = new User('Jim', 37, '[email protected]');

console.log(jim.getUserStats());

The code above logs this:

Name: Jack
Age: 35
Email: [email protected]

Differences Between module.exports and exports?

While working, you might come across the following syntax:


module.exports = {
  getName: () => {
    return 'Jack';
  },

  getLocation: () => {
    return 'Tokyo';
  },

  dob: '24.09.1984',
};

Here we’re assigning the functions and values we want to export to an exports property on module — and of course, this works just fine:

const { getName, dob } = require('./user');
console.log(
  `${getName()} was born on ${dob}.`
);

This logs the following:

Jack was born on24.09.1984.

So what is the difference between module.exports and exports? Is one just a handy alias for the other?

To better understand what I mean, let's change the code in index.js to record the value of the module:

console.log(module);

This produces:


Module {
  id: '.',
  exports: {},
  parent: null,
  filename: '/home/jack/Desktop/index.js',
  loaded: false,
  children: [],
  paths:
   [ '/home/jack/Desktop/node_modules',
     '/home/jack/node_modules',
     '/home/node_modules',
     '/node_modules' ] }

As you can see, module has an exports property. Let’s add something to it:

// index.js
exports.foo = 'foo';
console.log(module);

This outputs:

Module {
  id: '.',
  exports: { foo: 'foo' },
  ...

Assigning properties to exports also adds them to module.exports. This is because (initially, at least) exports is a reference to module.exports.

Conclusion

Today, modules have become an integral part of the JavaScript ecosystem . The use of module.exports allows us to export values, objects and styles from Node.js modules. Coupled with the use of require to import other modules, we have a complete ecosystem for composing large programs out of smaller parts. When we combine a number of modules that take care of unique parts of functionality, we can create larger, more useful, but easy to maintain applications and software systems.

Thanks for reading !

nodejs javascript node

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Node canvas is a Cairo backed Canvas implementation for NodeJS.

node-canvas is a Cairo-backed Canvas implementation for Node.js.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications? **[Hire NodeJs Developer](https://hourlydeveloper.io/hire-dedicated-node-js-developer/ "Hire NodeJs Developer")** to create a real-time, faster, and scalable...

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

How to get started Internationalization in JavaScript with NodeJS

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript.