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

Export and Import in Node.js

Learn how to share functions, variables and objects between JavaScript files using CommonJS exports and ES Module imports.

Export Import module.exports require() Named Exports Default Exports

1. What Are Export and Import?

In a Node.js application, we often create multiple JavaScript files to keep the application organized. Sometimes, a function or variable created in one file needs to be used in another file.

Export means making functionality available outside its module. Import means loading or accessing functionality that another module has exported.

For example, an application may contain:

  • math.js — contains calculation functions.
  • student.js — contains student-related functionality.
  • app.js — uses functions from other files.
Simple Definition: Export shares functionality from a file, and import allows another file to use that functionality.

2. Why Do We Need Export and Import?

  • Code Reusability: Use the same function in different files.
  • Less Duplication: Avoid writing the same logic repeatedly.
  • Better Organization: Keep related functions in separate files.
  • Easy Maintenance: Update a function in one place.
  • Readable Code: Keep the main application file simple.
  • Teamwork: Different developers can work on different modules.

3. How Export and Import Work

The following diagram explains how one file shares a function and another file uses it.

File 1

math.js

Defines the addition function.

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

Share the Function

module.exports = add;

Makes the function available to another CommonJS module.

↓
Import

app.js

const add = require("./math");

Loads the exported function.

↓
Output

Execute the Function

add(10, 20)

Result: 30

4. Export and Import Using CommonJS

CommonJS is a module system traditionally used in Node.js. It uses module.exports to expose functionality and require() to load that functionality.

Step 1: Create math.js

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

module.exports = add;

The add() function accepts two numbers and returns their sum. The statement module.exports = add exports the function.

Step 2: Create app.js

app.js
const add = require("./math");

const result = add(10, 20);

console.log("Addition:", result);

Expected Output

Addition: 30

Explanation

  1. math.js defines the function.
  2. module.exports makes the function available outside the module.
  3. require("./math") loads the exported function.
  4. add(10, 20) calls the function.
  5. console.log() displays the result.

5. Export Multiple Functions

We can export multiple functions together as properties of an object. This is useful when several functions belong to the same feature.

Step 1: Create calculator.js

calculator.js
function add(a, b) {
    return a + b;
}

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

function multiply(a, b) {
    return a * b;
}

module.exports = {
    add,
    subtract,
    multiply
};

Step 2: Import Functions in app.js

app.js
const calculator = require("./calculator");

console.log("Addition:", calculator.add(20, 10));
console.log("Subtraction:", calculator.subtract(20, 10));
console.log("Multiplication:", calculator.multiply(20, 10));

Expected Output

Addition: 30
Subtraction: 10
Multiplication: 200

Since the module exports an object, the importing file accesses each function through its property name using dot notation.

6. Import Multiple Functions Using Destructuring

Object destructuring lets us extract selected functions directly from the object returned by require().

app.js
const { add, subtract } = require("./calculator");

console.log(add(15, 5));
console.log(subtract(15, 5));

Expected Output

20
10

Here, add and subtract are extracted from the exported object. Their names match the exported property names.

7. Export and Import Using ES Modules

ES Modules use the export keyword to share functionality and the import keyword to use that functionality in another file.

Step 1: Create math.mjs

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

export function multiply(a, b) {
    return a * b;
}

Step 2: Create app.mjs

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

console.log("Addition:", add(10, 20));
console.log("Multiplication:", multiply(10, 20));

Expected Output

Addition: 30
Multiplication: 200

The curly braces in the import statement select the named exports that the file needs. The imported functions can then be called like normal JavaScript functions.

Note: This example uses the .mjs extension so Node.js identifies both files as ES Modules. A project can also use .js files with suitable package configuration.

8. Named Export and Default Export

ES Modules support named exports and default exports. A named export is imported using its exported name, while a default export is imported without curly braces.

Example: Default Export

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

Import the Default Export

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

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

Expected Output

Hello, Student!
Feature Named Export Default Export
Export syntax export function add() { ... } export default function greet() { ... }
Import syntax import { add } from "./math.mjs"; import greet from "./greeting.mjs";
Number per module Multiple named exports are allowed. Only one default export is allowed.

9. CommonJS vs ES Modules Flow

Both module systems allow files to share functionality, but they use different syntax.

CommonJS

Export

module.exports = add;
↓

Import

require("./math");

CommonJS module system

ES Modules

Export

export function add() { ... }
↓

Import

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

Standard JavaScript module system

10. Common Mistakes

Mistake Correct Approach
Forgetting to export a function. Export the function before trying to import it.
Using an incorrect file path. Check the relative path and filename.
Using curly braces incorrectly for a default import. Use curly braces for named imports, not for the default import.
Mixing CommonJS and ES Module syntax without checking configuration. Verify the module system used by the project.
Using a property name that was not exported. Check the exported names and match them when importing.

11. Practice Tasks

Task 1: Calculator Module

Create a calculator module with addition and subtraction functions. Export both functions and use them in another file.

Expected Output:
Addition: 30
Subtraction: 10

Task 2: Student Details

Create a module that exports a function returning a student's name and course. Import the function in another file and display the details.

Expected Output:
Student: Samadhan
Course: Node.js

Task 3: Greeting Module

Create a default-exported greeting function and import it into another file. Pass a name to the function and display the returned message.

Expected Output:
Hello, Student!

Summary

Export and import allow JavaScript files to share reusable functionality in Node.js applications. CommonJS uses module.exports to expose functions and values and require() to load them into another file. ES Modules use export and import, supporting both named exports and default exports. Named imports select specific exported values, while default imports load the module's primary exported value. These mechanisms improve code reusability, organization, readability and maintainability in Node.js projects.