How to Export Node.js Modules Using Exports

Read it in 7 Mins

Published
19th Oct, 2022
Views
2,057
How to Export Node.js Modules Using Exports

Understanding the use of modules in your projects is a much-needed skill in acing your software development career. 

Modules are useful for packaging, exporting, and sharing codes across different software development projects. 

With modules, you would not need to code every aspect of your project. Modules make it easy to reuse code from previous works or from third-party packages thereby reducing the time you would spend writing every line of code yourself. 

In this tutorial, you will learn a lot about modules, what they are, how to use them, and when to use them. 

Checkout our Node.js console application courses to speed up your full-stack development career. 

If you are ready for this tutorial, let’s get started… 

What are Node.js Modules?

The concept of modules is generally the same, even in Node.js. 

Node.js modules are encapsulated blocks of code that communicate with an external application based on the functionality they provide. Modules can be either a single file or a collection of files/folders. 

You will often find developers using modules in their projects because of their reusability and ability to break down complex pieces of code into manageable chunks. 

Modules in Node.js are classified into three types in general 

  • Core Modules 
  • local Modules 
  • Third-party Modules 

Core Modules: In Node.js, the built-in modules are known as core modules; this is because they came together as part of the platform and with the installation of Node.js. The required function can be used to load these modules into the program. 

Local Modules: Unlike built-in and external modules, local modules are created within your Node.js application. You, as a programmer, are responsible for creating a local module. 

Third-party modules: These can be found online via the Node Package Manager (NPM). These modules can be installed either locally or globally. React, Vue, Axios, and Angular are some popular examples. 

Example: 

  • npm install axios 
  • npm install web3 
  • npm install -g @angular/cli 

Formats of Node.js Modules

Because JavaScript originally did not support modules, a number of alternative formats have emerged over time. The following are the most important ones to be aware of: 

Asynchronous Module Definition (AMD): This format is used in browsers to define modules through a define() function. 

CommonJS (CJS): This Node.js format defines dependencies and modules using require and module.exports. The npm ecosystem is built on this format. 

ESM (ES Module): JavaScript now supports a native module format starting with ES6 (ES2015). It uses an export keyword to export a module's public API and an import keyword to import it. 

System.register: This format was created to accommodate ES6 modules within ES5. 

Universal Module Definition (UMD): This format is compatible with both browsers and Node.js. It's useful when a module needs to be imported by multiple module loaders. 

How to Export Object? 

Use the following steps to create your first module in NodeJs: 

Step 1: Create two files named index.js and modules.js in the same directory, and copy and paste the code below into your modules.js file.

const account = { 
  name: 'Daniel Obrian', 
  type: 'Checkings', 
  number: 9683563563, 
  swift: 'ATBNGLGA', 
  country: 'US' 
} 

Step 2: The node js modules can be exposed using the snippet below: 

exports.getAccount = account 
Step 3: Import the created module file into your index.js using the guide below: 
const modular = require('./modules') 
console.log(modular.getAccount) 
The above piece of code will produce this result when it is executed… 
// Output 
{ 
  name: 'Daniel Obrian', 
  type: 'Checkings', 
  number: 9683563563, 
  swift: 'GTBNGLGA', 
  country: 'US' 
} 

That’s how you to export objects in NodeJs… 

Module.exports  

To use module.exports in Node.Js, we will explain it using the example below: 

module.exports = { 
  getRoot: (num) => { 
    return num**2 
  }, 
  multiply: (num1, num2) => { 
    return num1 * num2 
  } 
} 

Create a file named modules.js in the same directory as your index.js file, and copy and paste the codes above into the just created file. 

The module.export syntax is responsible for packaging the code; then it can be consumed this way in your code. 

const {getRoot, multiply} = require('./modules') 
console.log(getRoot(5)) // Output: 25 
console.log(multiply(5, 2)) // Output 10 

When you execute the above lines of codes, it produces the 25 and 10. 

Require Function

Now it's time you understand why we use the require() function in NodeJs. The syntax for a require() function explains its usage clearly. 

var module = require('module_name'); 

Depending on what the module returns, the require() function will return a JavaScript object which can then be assigned to a variable. The following example shows how to get some dog breeds from an API using Axios. 

const axios = require('axios') 
const getBreeds = async () => { 
  try { 
    return await axios.get('https://dog.ceo/api/breeds/list/all') 
  } catch (error) { 
    console.error(error) 
  } 
} 

In the above code, the require() function returns an Axios object containing all the communication methods via HTTP. The Axios package has a method called get(). We used this get() method to retrieve the dog breeds from the URI endpoint. 

Gain software development mastery by enrolling in our full stack web developer course

Create and Export Modules

Let’s look at the various ways you can create, export, and consume a module using the examples below: 

Consider the following classes defined in our local module. 

// modules.js file 
class School { 
  constructor(_school, _address) { 
    this.school = _school 
    this.address = _address 
    this.students = [] 
  } 
addStudent(name) { 
    this.students.push(name) 
  } 
getStudents() { 
    return this.students 
  } 
} 
class NFT { 
  constructor(_name, _symbol) { 
    this.name = _name 
    this.symbol = _symbol 
    this.collection = [] 
  } 
mint(nft) { 
    nft.price = `${this.between(1, 5)} Eth` 
    nft.timestamp = new Date().toJSON() 
    this.collection.push(nft) 
  } 
 getNFTs() { 
    return this.collection 
  } 
between(min, max) {   
    return Math.floor( 
      Math.random() * (max - min) + min 
    ) 
  } 
} 

The Node.js modules can be exposed using the examples below. We can decide to export these classes using the following exports methods, and they will be represented like this: 

// Using the exports syntax 
exports.School = School 
exports.NFT = NFT 
Or you could use the module.exports method which will represent the exports syntax with one line of code: 
// Using the module.exports syntax 
module.exports = {School, NFT} 

After you’ve done your export, you can use these classes in any file by simply importing them as seen in this example: 

// index.js file 
const {School, NFT} = require('./modules') 
const school = new School('Harvard University', 'Cambridge, MA, United States') 
school.addStudent('James Milner') 
school.addStudent('Adler Morina') 
school.addStudent('Emeka Igwe') 
school.addStudent('Priyanka Nadar') 
const nft = new NFT('Ape Coin', 'APC') 
const metadata1 = { 
  title: 'Chief Ape', 
  description: 'The lost prince of Apes who returned   from a genetic lab and ready to save its follow apes from the oppressions of mankind.' 
} 
const metadata2 = { 
  title: 'Queen Ape', 
  description: 'A queen mother Ape banished from the land by her brother because of the throne. Now she is back with a crew for pay back.' 
} 
nft.mint(metadata1) 
nft.mint(metadata2) 
console.log('School Class...') 
console.log(school.getStudents()) 
console.log('NFT Class...') 
console.log(nft.getNFTs()) 
Here is the output on screen… 

That is how you create a module, export, and consume your NodeJs projects. 

Difference Between module.exports and Exports

There isn’t much significant difference between the methods in terms of their functionality. Here are some minor differences you can spot using the two module methods. 

Syntax: With exports, you‘ll have to specify individual items to be exported one line at a time, whereas, the module.exports syntax allows you to include all your exportables in one object as can be seen below: 

// export syntax 
exports.item1 = item1 
exports.item2 = item2 
// module.exports syntax 
module.exports = {item1, item2} 

We use the module to export a single class/variable/function from one module to another.  We use exports when we want to export multiple variables/functions from one module to another. 

Know more about What Are Callbacks in Node.JS

Conclusion

To summarize, segmenting codes for reusability is a critical skill to master if you want to be a great software developer. Modularizing your project is a sure way of improving your codes and also cutting down the time you spend writing them. But you still need to be careful of how you use modules in your code. Improper usage of modules could introduce some complexities to your code. 

For instance, external modules that are not optimized can increase the size of your application bundle, introducing another issue while providing solutions for you. We strongly advise you to make module integration a habit as you advance in your software development career. You can enroll yourself for the Node.js console application at KnowledgeHut to get deeply acquainted with both the stacks. 

We hope to see you again in the next tutorial. 

Frequently Asked Questions (FAQs)

1. Is module.exports better than export?

No, it’s rather based on convenience. Use module.exports for exporting multiple items and use exports to export single items easily. 

2. Are exports and module.exports similar?

Yes, they are similar in performance and result but different in syntax. Their items can be imported similarly as well. 

3. What are modules in Node.js?

Modules in NodeJs are a method of organizing blocks of code, functions, objects, and classes for code-sharing, reusability, and maintainability. 

4. What is the role of exports in Node.js?

Exports is a reserved keyword in NodeJs for specifying items to be imported into other files. 

5. How can I use exports? 

You use export by specifying the item to be exported. Thus the node js modules can be exposed using the syntax below. 

exports.item = item // item could be an object, function, class, etc. 

Profile

Darlington Gospel

Blog Author

I am a Software Engineer skilled in JavaScript and Blockchain development. You can reach me on LinkedIn, Facebook, Github, or on my website.

Want to become a sought-after web developer?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)