Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Modules
3.
Create Module
4.
Import Module
5.
Export Module
5.1.
Single Format
5.2.
Array Format
6.
Frequently Asked Questions
6.1.
Define Node.js.
6.2.
What is module.exports in Node.js?
6.3.
What is a require() function in Node.js?
6.4.
Is node js a programming language?
6.5.
Is node js used in the backend or frontend?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Creating and Exporting Modules in Node.js

Author Sagar Mishra
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hey Ninjas! What comes to your mind when you hear the word "Export"? Ofcourse, in real life, export means sending goods from one place to another. The same thing happens in the world of coding. Whenever we use the term export, we mean sending any variables, objects, or literals from one place to another.

How to Create and Export Modules in Node

You must be confused about why we are talking so much about export today. The reason behind this is today's topic of discussion is how to create and export modules in Node.js.

Modules

Before creating and exporting modules, let's first understand the modules. A module is simply a segment of JavaScript code which can be reused. It could be a .js file or a directory of .js files. The content in these files can be exported and used in other files.

Let's first try a simple Javascript function. Then we will move to the module creation and module export. We will create a file with the name index.js and make the required changes inside that.

index.js

function concatenation(x, y) {
  return x + y;
}

var myWord = concatenation("Coding ", "Ninjas");
console.log(myWord);

 

Output:

output

 

Explanation:

In the above program, we just created a concatenation function that adds two string values, as shown in the output screen. Later on, we created a variable named myWord and called the function. And, at last, we are printing the concatenated result.

Defining functions inside the main index.js works when you are a newbie or working at a beginner level, but in huge projects, it is not possible to create all the functions inside the main function. Defining and using functions in the main function may make a mess. Hence the term modules came into existence.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Create Module

As we are familiar with the reason behind the modules' existence, let us learn how we can create a module inside node JS.

To do so, we just have to create a new file, module.js, and then write the same function there. Let's have a look.

module.js

function concatenation(x, y) {
  return x + y;
}

 

index.js

var myWord = concatenation("Coding ", "Ninjas");
console.log(myWord);

 

Output:

output

 

Explanation:

Error! "concatenation is not defined". Just by doing the cut-paste task, we can face an error like this. We are facing this error because we have not yet linked our module.js file to the index.js file.

Import Module

A module can be imported, and its functionality can be reused. Node.js has the built-in require() function, which is the simplest way to use modules from the existing separate files. The basic functionality of require() is that it reads a JavaScript file, executes it, and proceeds to return the export object.

Hence, we will use a require() function to resolve the above error. Let's try again the same example with the require() function.

module.js

function concatenation(x, y) {
  return x + y;
}

 

index.js

var myModule = require("./module");

var myWord = myModule.concatenation("Coding ", "Ninjas");
console.log(myWord);

 

Output:

output

 

Explanation:

Oops! Again an error? But the error is different here. The error says, "myModule.concatenation is not a function". The program is showing an error because we have to call the export() function to use any function outside the file.

Export Module

The module.exports is a special object of a Javascript file in Node.js by default. Here the module is a variable that defines the current modules. And the exports() function is an object that will be exported as a module. So whatever we assign to the module.exports, it will be exported as a module. 

We can resolve the error that came in the last section by using the exports() function. Let's have a look.

module.js

function concatenation(x, y) {
  return x + y;
}


module.exports.concatenation = concatenation;

 

index.js

var myModule = require("./module");

var myWord = myModule.concatenation("Coding ", "Ninjas");
console.log(myWord);

 

Output:

output

 

Explanation:

We have used the module.exports function inside the module.js file to export the function to the main index.js file. 

Now the question is, "Can we export multiple functions at a time?" The answer is Yes. Let's check them out.

Note: There are two ways to export multiple functions in Node JS. 

Single Format

One way to export multiple functions is to write the "module.exports" for each function line by line. Let's take an example of this.

module.js

function concatenation(x, y) {
  return x + y;
}

function greet(x) {
  return x;
}

module.exports.concatenation = concatenation;
module.exports.greet = greet;

 

index.js

var myModule = require("./module");

var myWord = myModule.concatenation("Coding ", "Ninjas");
console.log(myWord);

var myGreet = myModule.greet("Welcome to Coding Ninajs");
console.log(myGreet);

 

Output:

output

 

Explanation:

As you can see, both functions are exported separately in the module.js file. But writing the same lines for each function in a huge project will be a tough task. 

To overcome this problem, we have the array format also. Let's have a look.

Array Format

In the array format, we can export multiple functions at a time just by writing the function name. Let's quickly move to the example for better understanding.

module.js

function concatenation(x, y) {
  return x + y;
}

function greet(x) {
  return x;
}

module.exports = { concatenation, greet };

 

index.js

var myModule = require("./module");

var myWord = myModule.concatenation("Coding ", "Ninjas");
console.log(myWord);

var myGreet = myModule.greet("Welcome to Coding Ninajs");
console.log(myGreet);

 

Output:

output

 

Explanation:

The output will remain the same for the array format also. Additionally, this will save time too for the user. Hence, this is a good practice to use the array format instead of a single format.

As we have now discussed all our topics, let's now discuss some faqs.

Frequently Asked Questions

Define Node.js.

Node.js is a free, open-source Javascript runtime environment built on Chrome's v8 engine. It is used to build fast and scalable web apps.

What is module.exports in Node.js?

The module.exports is a special object of a Javascript file in Node.js by default. Here the module is a variable that defines the current modules.

What is a require() function in Node.js?

Node.js has the built-in require() function, which is the simplest way to use modules from the existing separate files.

Is node js a programming language?

No, node js is a runtime environment only. It is used to run the JS files outside the browser.

Is node js used in the backend or frontend?

It is misunderstood by many developers that node is only used in the backend. Rather we can use it in both frontend and backend.

Conclusion

This article discusses the topic of how to create and export modules in node js. In detail, we have seen the definition module. Along with this, we have seen how to create, import and export the modules with examples.

We hope this blog has helped you enhance your knowledge to create and export modules in node js. If you want to learn more, then check out our articles.

 

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
How to use Class in Node.js
Next article
Managing NPM Versions and Packages
Live masterclass