Creating and Exporting Modules in Node.js

Manvi Chaddha
Last Updated: May 13, 2022

Introduction

What comes to mind when you hear the word import and export?

The first thought is that importing means a product or service brought into one country from another, and exporting means a product or service sent into one country from another. As we export and import goods in real life, we do so in computer programming as well. In computer programming, we deal with variables and functions, so in programming, we will learn how to import and export modules, variables, and functions. This blog will teach creating and exporting modules in Node.js. Let's get started.

Module System in Node.js

You might already know that there is a window object in web browsers that represents the global scope. All the variables and functions defined globally are accessible using 'window,' or all the variables and functions have a global scope in the case of Client-Side JavaScript. That means in the case of client-side JavaScript; whether we write console.log('Hello World') or window.console.log('Hello World'), it's the same thing. However, we do not append global to console.log; it is done automatically by the JavaScript v8 engine.  

However, Node.js does not support window object. Instead, there is a global namespace object. The global namespace object is quite different from the window object in client-side JavaScript, as illustrated below.

’The variable x is not accessible by the window.x because the variable x is not scoped globally in Node.js. Node.js uses a concept of modularity; In the Node.js module system, each file is treated as a separate module. Let's try to understand the module with a simple example, the below app.js file contains some JavaScript mode, and in the end, we are logging the content of the module using console.log

// A simple node.js module
var x = 10
console.log(x);

console.log(module)

The output is:

10

Module {

  id: '.',

  path: '/workspaces/Java/first-app',

  exports: {},

  parent: null,

  filename: '/workspaces/Java/first-app/app.js',

  loaded: false,

  children: [],

  paths: [

    '/workspaces/Java/first-app/node_modules',

    '/workspaces/Java/node_modules',

    '/workspaces/node_modules',

    '/node_modules'

  ]

}

 

A module is a JSON object with key-value pairs.

The variables and functions defined in one module are scoped to that file only and are not globally accessible. In the case of real-world applications, the entire application is divided into small modules. To reuse the variables and functions defined in one module, we need to import them. The following sections will illustrate the concept of creating and exporting modules in node.js

Creating a Module in Node.js

Creating a module in Node.js is quite simple. Every time you create a JavaScript file, you create a new module. So the below add.js file is a module

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

Exporting a Module in Node.js

The module.exports is a special object included in the JavaScript file in the Node.js application by default. Here the module is a variable representing the current module, and the exports is an object that will be exposed as a module. So whatever you assign to the module.exports will be exposed/exported as a module. To verify that a variable or a function is successfully exported, you can use the console.log(module); the values corresponding to the exports key in the JSON module object will contain the information of the exported module.

We can export literals and functions using the module.exports as illustrated below

// A variable
var URL = 'https://abcd.fgh';

// The log function needs to be exported
// in the main file
function log(message){
    console.log(message);
}

// Exporting a variable
module.exports.myURL = url;

// Exporting a function
module.exports.mylog = log;
console.log(module)

The output is as follows:

The values corresponding to the exports key are not empty, indicating the successful export of the variable and function.

You can also attach an anonymous function to export object as shown below:

module.exports = function(msg){
    console.log(msg)
}

console.log(module)

The output is:

You can also export a function as a class. A function can be treated as a class.

module.exports = function(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function(){
        return this.firstName + ' ' + this.lastName;
    }
}
console.log(module)

The corresponding output is:

Importing Module in Node.js

The major advantage of modularity in Node.js is that it provides reusability of code over different files. A module can be imported, and its functionality can be reused. Node.js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and proceeds to return the exports object.

Consider that there are two modules, app.js, and myapp.js. The myapp.js module has an add function, and this function is exported; the module app.js will import and reuse it. 

Filename: myapp.js

// The add function is exported and it
// will be reused in the app.js file
function add(a, b){
    return a + b;
}

// Exporting the function add
module.exports.add = add;


Filename: App.js

// importing the add function from myapp.js file
const func = require('./myapp');

const result = func.add(10, 20);
console.log('The result is: ', result);
console.log(module)

The output is:

The values corresponding to the children key indicates successful import.

Let's take a look at another example wherein two functions are exported from the myapp.js file and will be imported into the app.js file.

Filename: myapp.js

// The add function is exported and it
// will be reused in the app.js file
function add(a, b){
    return a + b;
}

// The subtract function is exported and it
// will be reused in the app.js
function subtract(a, b){
    return a - b;
}

// Exporting the function add and subtract
module.exports = { add, subtract };
console.log(module)

Filename: app.js

In this file, apart from reusing the functions exported from the myapp.js file, we will also use the object returned by the require function.

// importing the add function from myapp.js file
const func = require('./myapp');

console.log(func);

// reusing the functions
console.log(func.add(10, 20));
console.log(func.subtract(30, 20));

The output is:

We can also use destructuring in the app.js file as shown below:

// importing the add function from myapp.js file
const {add, subtract}= require('./myapp');

console.log(add(10, 20));
console.log(subtract(30, 20))

Apart from importing from local modules, we can also import from core modules, that is, the modules which are inbuilt in Node.js and third-party modules like express. The third-party modules are installed using a package manager like npm.

// Importing core modules
const filesystem = require('fs')
const os = require('os')

console.log(filesystem)
console.log(os)

The output will 
{

  appendFile: [Function: appendFile],

  appendFileSync: [Function: appendFileSync],

  access: [Function: access],

  accessSync: [Function: accessSync],

  chown: [Function: chown],

  chownSync: [Function: chownSync],

     },

…………………………..

……………………………

…………………………….

}

Importing third party packages

const express = require('express')
const mongoose = require('mongoose')

console.log(express)
console.log(mongoose)

The output is:

[Function: createApplication] {

  application: {

    init: [Function: init],

    defaultConfiguration: [Function: defaultConfiguration],

    lazyrouter: [Function: lazyrouter],

    handle: [Function: handle],

    use: [Function: use],

    route: [Function: route],

……………………………………………………

……………………………………………………..

}]

So far, we have seen Creating and Exporting Modules in Node.js; let's look at some of the frequently asked questions related to the same.

Frequently Asked Questions

Q1) What is Node.js?

Ans 1) Node.js is a JavaScript runtime environment built on Chrome’s v8 engine. It is used to build fast and scalable web applications.

Q2) What is module.exports in Node.js?

Ans 2) The module.exports is a special object which is included in the JavaScript file in the Node.js application by default. Here the module is a variable representing the current module, and the exports are an object that will be exposed as a module. So whatever you assign to module.exports will be exposed/exported as a module.

It's used in Creating and Exporting Module in Node.js

Q3) What is require function in Node.js?

Ans 3)  Node.js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and proceeds to return the exports object.

It's used in creating and Exporting Module in Node.js

Key Takeaways

This blog discussed exporting and importing modules in Node.js with many examples. It's time for you now to explore Node.js and the module system of Node.js in depth.

A common problem faced by all of us is that we prepare well, but during online assessments, we cannot solve the questions on time. To overcome this, Coding Ninjas have come up with an online mock test series. The mock tests for leading companies like Amazon, Microsoft, Google, Adobe, Flipkart, TCS, Wipro, and Accenture are free. Our team of experts has curated and designed these online mock test series to help you prepare better for your coding interview rounds. In this online test series, you will get multiple tests that include the latest coding interview questions. Start preparing for the 2021 Amazon, Microsoft, etc., tech interviews now.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think