Languages
[Edit]
EN

Node.js - how to use module exports

0 points
Created by:
mkrieger1
516

In this article, we would like to show you how to use module exports in Node.js.

1. Introduction 

In Node.js, modules are the blocks of encapsulated code, functionality that can be shared and reused across projects. They also helps to organize the code, leading to easier to understand, debug and maintain the application.

2. Module formats

There are a few different types of module formats:

  1. CommonJS - format used in Node.js. Uses module.exports to export modules and require keyword to import them.
  2. ES Module (ESM) - uses export keyword to export modules and an import keyword to import them (as ES6 native module format).
  3. Asynchronous Module Definition (AMD) - 
  4. Universal Module Definition (UMD) -  can be used both in the browser and in Node.js. This format is useful when a module has to be imported by many different module loaders.
  5. System.register - designed to support ES6 modules within ES5

Note:

In this article we use the default for Node.js - CommonJS format.

3. Create and export module

To create a module, simply create a new file with some reusable code and use modules.export to export the functionality. 

In below example we create and export User class in separate users.js file.

// ONLINE-RUNNER:browser;

module.exports = class User {
    constructor(id, name, age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
 
    display() {
        console.log(`id: ${this.id}, name: ${this.name}, age: ${this.age}`);
    }
 }

Note:

Go to te following article to see full explanation of the example: Node.js - export class from module.

4. Import module

After creating and exporting a module, import it in the main project file (e.g index.js) using the require keyword.

const User = require('./user');

Now you are able to use its functionality.

Practical example:

const User = require('./user');

const user1 = new User(1, 'Tom', 23);

user1.display();

Output:

id: 1, name: Tom, age: 23

Related posts

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join