Import and Export Modules in NodeJS
Tags: node, javascript, beginners, webdev
Published: 2022-11-02 13:40:15


## 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](https://mkdaycode.blogspot.com/2022/10/blog-post_12.html). 

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:_**

```javascript
 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
 };
```

**_index.js:_**

```javascript
 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.

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

1. Core modules

1. Node_modules

1. 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](https://www.w3schools.com/nodejs/ref_modules.asp) of them.

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

**_index.js:_**

```javascript
 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
```

## 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.

```javascript
 const express = require('express');
```
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

```javascript
const first = require('./example-folder/first');
```
- Using absolute path

```javascript
const first = require('/Home/Documents/blog-code-snippets/example-folder/first.js');
```

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.


```javascript
 module.exports = {
    num,
    greet,
    Student
 };
```

## 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:**_

```javascript
 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.');
    }
 };
```

_**index.js:**_

```javascript
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.
```

## 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:_**

```javascript
 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 };
```

_**index.js:**_

```javascript
const first = require('./example-folder/first.js');
 
const student = new first.Student('Bob', 100);
 
student.showMarks(); // student Bob has 100 marks.
```

## 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](https://mkdaycode.blogspot.com/2022/10/blog-post_12.html).

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](https://nodejs.org/docs/v0.4.2/api/modules.html).

Happy Coding!

_Image by CopyrightFreePictures from Pixabay._

[![ko-fi](https://cdn.ko-fi.com/cdn/kofi2.png?v=3)](https://www.ko-fi.com/mkdaycode)