Understanding Module In Node.js

NodeJS Module

NodeJS is a JavaScript based framework built on Chrome’s V8 engine. NodeJS is used for building the asynchronous, event driven, and I/O based applications. Module is one of the major parts of NodeJS. In this article, we will learn about the modules.

What is Module ?

Module is a set of reusable code that encapsulates related code into a single unit of code. Using module, we insert the related code in a file and use this file wherever we require. So, the code of module doesn’t conflict with the remaining part of  the application. If we try to use the code of module without any permission, then we will get an error.
Let us take an example.

First we create a Main.js file and insert the below code in this file.

code

In the above code, we create two functions - CallFun function takes the name of another function as parameter and invokes that function. At the end of this file, we invoke the CallFun function and send the Call as parameter value. This Main.js file is a JavaScript file.

code

In the above code, we include the Main.js module using required function. Now, if we run the application, the following output will occur.

output

Let us take another example.

Main.js file

Main.js

App.js file

app.js

Output

Output

In this example, we include the Main.js module into the App.js file, using require, and trying to invoke CallFun method. But, we get the error that “CallFun is not defined”. If we want to use “CallFun” function into App.js file, we first need to export this function. Let us see how to export a function of module.

Main.js

Main.js

App.js

App.js

Output

Output

In this example, we export the CallFun method using export. If you want to use a method of module, then you must export that method(s).

We have another way to export a method of module in an application, as shown below.

Method 1

Main.js

Main.js:

App.js

App.js:

Output

Output:

Method 2

Main.js

Main.js:

App.js

App.js:

Output

Output

Export Multiple Method and Property of Module

Now, we learn how to export multiple methods and property of module.

Main.js

Main.js

App.js

App.js

Output

Output

I hope you liked this article. If you have any query or doubt, you can post it in the comment section. Thanks for reading the article.

Up Next
    Ebook Download
    View all
    Learn
    View all