Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

ES Modules in Node.js

Learn how to use the modern JavaScript module system in Node.js with import, export, named exports, default exports and practical examples.

ES Modules import export Named Export Default Export

1. What Are ES Modules?

ES Modules (ESM) are the standard JavaScript module system. They allow developers to divide code into separate files and share functions, variables, classes and other values between those files.

ES Modules use two main keywords:

  • export: Makes selected functionality available to other modules.
  • import: Loads exported functionality into another module.

For example, we can define a multiplication function in math.mjs and use it in app.mjs. This avoids duplicating the same function in multiple files.

Definition: ES Modules provide a standard way to export functionality from one JavaScript module and import it into another.

2. Why Do We Use ES Modules?

  • Code Reusability: Share functions between files.
  • Better Organization: Keep related functionality in separate modules.
  • Easy Maintenance: Modify a feature in its own module.
  • Named Imports: Import the specific values needed from a module.
  • Default Exports: Export one primary value from a module.
  • Standard Syntax: Use the same module syntax in modern JavaScript environments that support ESM.

3. How ES Modules Work

An ES module exports a function or value. Another module imports that value and uses it in its own code.

Step 1: Define

math.mjs

function add(a, b) { ... }

Create the reusable function.

↓
Step 2: Export

export

export function add(a, b) { ... }

Expose the function.

↓
Step 3: Import

app.mjs

import { add } from "./math.mjs";

Load the exported function.

↓
Step 4: Execute

Call the Function

add(10, 20)

Result: 30

4. Named Exports

A named export exports a function, variable or class using its declared name. A module can contain multiple named exports.

Step 1: Create math.mjs

math.mjs
export function add(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}

export const instituteName = "CIIT Training Institute";

Step 2: Import Values in app.mjs

app.mjs
import { add, subtract, instituteName } from "./math.mjs";

console.log(instituteName);
console.log("Addition:", add(20, 10));
console.log("Subtraction:", subtract(20, 10));

Expected Output

CIIT Training Institute
Addition: 30
Subtraction: 10

Explanation

  1. The add() function is exported by name.
  2. The subtract() function is also exported by name.
  3. The instituteName constant is another named export.
  4. The importing file uses curly braces to select the named exports.
  5. The imported functions are called like normal functions.
Remember: Named imports normally use the same names as their exports. If you want different local names, use the as keyword.

5. Import Using an Alias

An alias allows an imported value to be referred to by a different local name. It is useful when avoiding naming conflicts or choosing a more meaningful name.

app.mjs
import { add as calculateSum } from "./math.mjs";

console.log(calculateSum(15, 25));

Expected Output

40

Here, the exported function is named add, but it is used locally through the name calculateSum.

6. Default Export

A default export is used when a module has one primary value or function that it wants to export as its default. A module can have only one default export.

Step 1: Create greeting.mjs

greeting.mjs
export default function greet(name) {
    return "Hello, " + name + "!";
}

Step 2: Import in app.mjs

app.mjs
import greet from "./greeting.mjs";

console.log(greet("Student"));

Expected Output

Hello, Student!

Notice that the default import does not require curly braces. The importing file can choose its local name for the default import.

7. Named Export vs Default Export

Feature Named Export Default Export
Syntax export function add() { ... } export default function greet() { ... }
Imports Usually uses curly braces. Does not use curly braces for the default import.
Number per module A module can have multiple named exports. A module can have only one default export.
Import naming Use the exported name or an alias. The importing file chooses a local name.

8. Import All Named Exports

We can import all named exports from a module under a single namespace object using the * as syntax.

app.mjs
import * as math from "./math.mjs";

console.log(math.add(10, 5));
console.log(math.subtract(10, 5));

Expected Output

15
5

Here, math acts as a namespace object for the module's named exports. The functions are accessed using dot notation.

9. ES Modules with Node.js

Node.js supports ES Modules. There are two common ways to identify a file as an ES module.

Method 1: Use the .mjs Extension

Files ending in .mjs are treated as ES modules. For example, use app.mjs and math.mjs.

Terminal
node app.mjs

Method 2: Configure package.json

In a Node.js project, adding "type": "module" to package.json makes ordinary .js files in that package scope use ES Module syntax.

package.json
{
    "type": "module"
}

With this configuration, you can use app.js and math.js with import and export.

Important: Do not mix CommonJS and ES Module syntax indiscriminately. Check your file extension and package configuration so Node.js interprets the file correctly.

10. Practical Example: Student Module

Let's create a module that returns student details and import it into the main application.

Step 1: Create student.mjs

student.mjs
export function getStudent(name, course) {
    return {
        name,
        course
    };
}

Step 2: Create app.mjs

app.mjs
import { getStudent } from "./student.mjs";

const student = getStudent("Samadhan", "Node.js");

console.log("Student:", student.name);
console.log("Course:", student.course);

Expected Output

Student: Samadhan
Course: Node.js

The student module owns the logic for creating a student object. The main application imports and uses that functionality.

11. ES Module Execution Flow

Module A

student.mjs

export function getStudent() { ... }

Defines and exports functionality.

↓
Import Statement

app.mjs

import { getStudent } from "./student.mjs";

Imports the named export.

↓
Function Call

Create Student

getStudent("Samadhan", "Node.js")

Receives a student object.

↓
Result

Display Details

Student: Samadhan

Course: Node.js

12. Common Mistakes

Mistake Correct Approach
Using curly braces for a default import. Import a default export without curly braces.
Importing a named export using the wrong name. Match the exported name or use an alias.
Using an incorrect file path. Verify the relative path and file extension.
Forgetting to export a function. Export the function before importing it elsewhere.
Running an ES module as CommonJS. Check the file extension and package configuration.

13. Practice Tasks

Task 1: Create a Calculator Module

Export addition and multiplication functions from calculator.mjs. Import them into app.mjs and display the results.

Expected Output:
Addition: 30
Multiplication: 200

Task 2: Use a Default Export

Create a default-exported function that returns a welcome message. Import the function in another file and display it.

Expected Output:
Welcome to Node.js Modules!

Task 3: Create a Student Module

Export a function that accepts a student's name and course and returns an object. Import it and display both properties.

Expected Output:
Student: Pradnya
Course: JavaScript

Summary

ES Modules are the standard JavaScript module system used to organize code into reusable files. The export keyword makes functions, variables and classes available to other modules, while import allows another file to use the exported values. Named exports support sharing multiple values, and a default export provides one primary exported value from a module. Node.js supports ES Modules through the .mjs extension or suitable package configuration. These features improve code organization, reusability, readability and maintainability in Node.js applications.