Node.js - export class from module

0 points
Created by:

In this article, we would like to show you how to export class from module in Node.js.

Below we present how to export class from module1.js to index.js file.

Project structure:

   ├── index.js
   ├── user.js
   └── package.json

Steps to follow:

1. In module1.js file export the class using module.exports.

Practical example:

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

2. In index.js file import the class from module1.js using require(). From now you can create class objects and use its methods as presented below.

Practical example:

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

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


3. Now you can run the project from terminal to see the output using the following command:

node index.js


id: 1, name: Tom, age: 23
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.

❤️💻 🙂