Tutorial

NodeJS Export and Import Modules

Published on August 3, 2022
Default avatar

By Rambabu Posa

NodeJS Export and Import Modules

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In my previous posts, we have discussed about “How to install Enide Studio 2014 IDE” and also “How to create a Node JS Application”. Before discussing about “How to create new Node JS Modules and How to reuse them in other Node JS Modules”, first of all we need to have some good knowledge about how to export and import a Node JS module. In this post, we are going to discuss the following two important Node JS concepts theoretically.

  • How to export a Node JS Module
  • How to import a Node JS Module

We will use this knowledge especially in next post, but also in all my coming post’s examples.

Export a Node JS Module

First and foremost thing we need to understand is why we need to export a Node JS Module? Node JS has provided almost all required modules (We can check this updates on its official website: https://www.npmjs.com/. It is also known as Node JS Module Repository). But in some realtime applications, we may have some application functionality, which is used many places in that application but not available at Node JS Module Repository. In this scenario, to get Reusability benefit, we need to create our own new Node JS module. Just creating new Module is not enough to use it in other modules of the system. We need to export this module so that other modules will reuse it. If you are a UI or Java Developer, then is familiar to you. If we have any common or reusable component in Java-based application, then we develop it as a separated project, create a Jar file and add it at required projects classpath. Don’t worry too much about how to create a Node JS Module at this point. We will discuss how to create our own new Node JS Module in future post. Node JS Platform has provided a technique to export the following things so that other modules can reuse them without redefining.

  • Variable
  • Function
  • Module

To export all these three, we have to use same technique. Node JS has provided an Object “exports” to do this. Syntax: NodeJS-export-module-1 We will see one by one now with some examples. Here we are discussing them theoretically only. We will take one realtime scenario and implement one Node JS Application in my next post. How to export a JavaScript Variable We use Node JS “exports” object to export a Node JS Module’s Variable so that other Modules can reuse it. In realtime, we don’t just export a Variable. However just for practice purpose and also to make it clear to beginners, we are discussing this separately. Syntax: NodeJS-export-module-2 Example: Let us assume that we have created a simple Node JS Project with one JavaScript file: pi.js file with the following content.

var PI = 3.1416
exports.PI = PI;

Here we have exported PI variable as exports.PI with name PI. That’s means other Node JS project can use this variable very easily just using PI name. How to export a JavaScript Function: We use Node JS same “exports” object even to export a Node JS Module’s JavaScript function so that other Modules can reuse it. In realtime, we may do this but it is not recommended to use always. Syntax: NodeJS-export-module-3 Example: Let us assume that we have created a simple Node JS Project with one JavaScript file: arthmetic.js file with the following content.


function add(a,b){
return a + b;
}

function sub(a,b){
return a - b;
}

function mul(a,b){
return a * b;
}

function div(a,b){
return a / b;
}

exports.add = add
exports.sub = sub
exports.mul = mul
exports.div = div

Here we have exported all 4 JavaScript functions separately. That’s means other Node JS project can reuse them directly. It is a simple Arithmetic application. However if we take some realtime Node JS Applications, we can observe plenty of JavaScript files and each file may contain plenty of functions. In this scenario, it is very tedious process to export each and every function separately. To resolve this issue, we need to use Exporting a Node JS module technique as described below. How to export a Node JS Module: We use Node JS same “exports” object even to export a Node JS Module so that other Modules can reuse it. In realtime, it is recommended. Syntax: NodeJS-export-module-4 Example: Let us assume that we have created a simple Node JS Project with one JavaScript file: arthmetic.js file with the following content.

exports.arthmetic = {

var PI = 3.1416;
function add(a,b){
return a + b;
}

function sub(a,b){
return a - b;
}

function mul(a,b){
return a * b;
}

function div(a,b){
return a / b;
}
}

Here we have exported all 4 JavaScript functions and PI variable with just one exports statement. That’s means other Node JS project can reuse all functions and PI very easily.

Import a Node JS Module

If we observe a Node JS Application or Module, it may dependent on other existing Node JS modules or our own Modules. The major advantage of Modularity is reusability. We don’t need to redevelop the same existing functionality. We can import a Module and reuse that module functionality very easily. How to import a Node JS Module: We use same technique to import our modules or existing Node JS Modules. Node JS Platform has provided a function call “require()” to import one module into another. Syntax: NodeJS-import-module-1 Here module-name is our required Node JS module name. some-name is reference name to that module. This require() call import the specified module and cached into the application so that we don’t need to import it again and again. Example:

  • To import our own Node JS module

    var arthmetic = require("arthmetic");
    
  • To import existing Node JS Module Import Node JS “express” module;

    var arthmetic = require("express");
    

    Import Node JS “mongoose” module;

    var mongoose = require("mongoose");
    

This require() call is similar to “import” statement in Java. We use import statement to import a package, class, interface etc into another class or interface. Now we got some knowledge about how to export and import a Node JS module. We will use this knowledge to create our own Node JS Modules in next post.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Rambabu Posa

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 10, 2020

How to use the method of a module that returns a promise into our current module.

- Adi Madan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 1, 2020

    I could identify an issue while using the Js arthmetic.js. It was showing error , so after re framing the code the error was gone. Re-framed Code var arithmetic = { //var PI = 3.1416, add : function (a,b){ return a + b; }, sub : function (a,b){ return a - b; }, mul : function (a,b){ return a * b; }, div : function (a,b){ return a / b; } }; module.exports = arithmetic; In the sample js file this is imported using var myLogModule = require(‘./arithmetic.js’); var output = myLogModule.add(1,2); console.log("Result of arithmetic calculation : "+output); Just want to check if you did not see any issues with the code mentioned in the tutorial. Also let me know how the variable can be passed .

    - Rahul M G

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 2, 2016

      its a nice expanation for beginner to understand the concept of exporting and importing node js module.

      - preeti chauhan

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Get our biweekly newsletter

        Sign up for Infrastructure as a Newsletter.

        Hollie's Hub for Good

        Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

        Become a contributor

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        Welcome to the developer cloud

        DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

        Learn more
        DigitalOcean Cloud Control Panel