DEV Community

Cover image for Import and Export Modules in NodeJS
MkDay
MkDay

Posted on

Import and Export Modules in NodeJS

Introduction

As we know there are slight differences between core JavaScript and NodeJS. Today we’re going to discuss one of the features that are used differently in JavaScript and NodeJS. Which is import and export modules in NodeJS.

Note: You can learn about Import Export Modules in JavaScript here.

Let’s jump into the topic of how to import and export modules in NodeJS.

In NodeJS, each file is considered a module since Node uses the CommonJS module system. And variables, functions, and classes in a module are private to that particular file (module). If we want to use them outside of the module, we have to export them first and, import them into the place where we want to use them.

Look at the following example.

Here we have two modules.

  • index.js

  • /example-folder/first.js (‘first.js’ module in the folder called ‘example-folder’)

/example-folder/first.js:

 const num = 10;

 const greet = (name) => {
    console.log('Hello, ' + name);
 };

 class Student {
    constructor(name, marks) {
        this.name = name;
        this.marks = marks;
    }

    showMarks() {
        console.log('student ' + this.name + ' has ' + this.marks + '   marks.');
    }
 };

 module.exports = {
    num,
    greet,
    Student
 };
Enter fullscreen mode Exit fullscreen mode

index.js:

 const first = require('./example-folder/first');

 console.log(first.num); // 10

 first.greet('Tom'); // Hello, Tom

 const student = new first.Student('Bob', 100);

 student.showMarks(); // student Bob has 100 marks.

Enter fullscreen mode Exit fullscreen mode

There are three types of import-export that can be done in NodeJS.

  1. Core modules

  2. Node_modules

  3. JavaScript files

Let’s explore the above types.

1. Require core modules

For example, if we want to create a server object, we have to import a built-in module for NodeJS called http.

These built-in modules are called core modules in NodeJS and there is a list of them.

The syntax for importing built-in modules is straightforward, just put the name of the module inside quotation marks.

index.js:

 const http = require('http');


 //create a server object:
 http.createServer((req, res) => {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
 }).listen(8080); //the server object listens on port 8080
Enter fullscreen mode Exit fullscreen mode

2. Require Node_Modules

Let’s say we have installed the express package and therefore we have the Node_Modules folder automatically. And we want to import the express package from the Node_Modules folder. Then we use the following syntax.

 const express = require('express');
Enter fullscreen mode Exit fullscreen mode

Here express is not a,

  • built-in module or
  • JavaScript file that its path begins with ‘/’ or ‘./’

3. Require JS files

All the modules that we create can be imported using the following two ways.

  • Using relative path
const first = require('./example-folder/first');
Enter fullscreen mode Exit fullscreen mode
  • Using absolute path
const first = require('/Home/Documents/blog-code-snippets/example-folder/first.js');
Enter fullscreen mode Exit fullscreen mode

Now we know how to import three types of modules. And let’s talk about how to export items from a module.

4. module.exports

module.exports can be used to export multiple things at once. Let’s look at our starting example. There we export a variable, function, and a class.

We can do so since module.exports is an object. And we can assign properties to it.

 module.exports = {
    num,
    greet,
    Student
 };
Enter fullscreen mode Exit fullscreen mode

5. exports

Also, exports method allows us to export a single item at a time. Unlike module.exports we cannot export multiple items at once using the exports keyword. Look at the following example, in there we have used it for the variable, function, and class separately.

/example-folder/first.js:

 exports.num = 10;

 exports.greet = (name) => {
    console.log('Hello, ' + name);
 };

 exports.Student = class Student {
    constructor(name, marks) {
        this.name = name;
        this.marks = marks;
    }

    showMarks() {
        console.log('student ' + this.name + ' has ' + this.marks + ' marks.');
    }
 };
Enter fullscreen mode Exit fullscreen mode

index.js:

const first = require('./example-folder/first.js');

console.log(first.num); // 10

first.greet('Tom'); // Hello, Tom

const student = new first.Student('Bob', 100);

student.showMarks(); // student Bob has 100 marks.
Enter fullscreen mode Exit fullscreen mode

6. module.exports vs. exports

module.exports and exports both are objects. But it only exports things in the module.exports if we use both of them in the same file.

Look at the following example, here we only export the class Student inside module.exports and it is the only thing that can be exported without getting errors.

/example-folder/first.js:

 exports.num = 10;

 exports.greet = (name) => {
    console.log('Hello, ' + name);
 };

 class Student {
    constructor(name, marks) {
        this.name = name;
        this.marks = marks;
    }

    showMarks() {
        console.log('student ' + this.name + ' has ' + this.marks + ' marks.');
   }
};


 module.exports = { Student };
Enter fullscreen mode Exit fullscreen mode

index.js:

const first = require('./example-folder/first.js');

const student = new first.Student('Bob', 100);

student.showMarks(); // student Bob has 100 marks.
Enter fullscreen mode Exit fullscreen mode

7. ECMA Script Module - import export

This is simply called ESM, it allows you to use JavaScript import & export keywords instead of require and module.exports keywords while importing and exporting items. To use them you have to set the type: module at package.json file.

Here I’m not going to discuss how to use import and export keywords but you can read about it here.

So I hope now you have a better understanding of how to import and export modules in NodeJS and if you want to learn more about it read the NodeJS.org docs.

Happy Coding!

Image by CopyrightFreePictures from Pixabay.

ko-fi

Top comments (0)