Node.js Fundamentals

Learn Node.js from scratch including core concepts, modules, and basic server development.

beginner Backend Development 5 hours

Chapter 3: Node.js Modules and require()

Chapter 3 of 15

Chapter 3: Node.js Modules and require()

3.1 Core Modules

Node.js includes built-in core modules that provide essential functionality. These modules don't need installation.

Common Core Modules:

  • fs: File system operations
  • http: HTTP server and client
  • path: File and directory path utilities
  • url: URL parsing and resolution
  • querystring: URL query string parsing
  • events: Event emitter functionality
  • stream: Streaming data
  • crypto: Cryptographic functionality
  • os: Operating system utilities
  • util: Utility functions
// Using core modules
const fs = require('fs');
const http = require('http');
const path = require('path');
const os = require('os');

// File system operations
fs.readFile('file.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

// Path operations
const filePath = path.join(__dirname, 'data', 'file.txt');
const ext = path.extname(filePath); // .txt

// OS information
console.log(os.platform()); // win32, darwin, linux
console.log(os.totalmem()); // Total memory

3.2 Creating Custom Modules

Node.js uses CommonJS module system. Create reusable modules by exporting functions and objects.

Module.exports:

// math.js - Export object
module.exports = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => a / b
};

// app.js - Import and use
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.multiply(4, 5)); // 20

Exporting Functions:

// utils.js
function formatDate(date) {
    return date.toISOString();
}

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

module.exports = {
    formatDate,
    capitalize
};

// Or export individually
exports.formatDate = formatDate;
exports.capitalize = capitalize;

Exporting Classes:

// User.js
class User {
    constructor(name, email) {
        this.name = name;
        this.email = email;
    }
    
    greet() {
        return `Hello, ${this.name}!`;
    }
}

module.exports = User;

// app.js
const User = require('./User');
const user = new User('John', 'john@example.com');
console.log(user.greet()); // Hello, John!

3.3 ES6 Modules (Alternative)

Node.js also supports ES6 modules using import/export syntax.

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

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

// app.mjs
import { add, subtract } from './math.mjs';
console.log(add(2, 3)); // 5

// Or use "type": "module" in package.json
// Then use .js files with import/export

3.4 Module Resolution

Understanding how Node.js finds and loads modules.

Module Resolution Order:

  1. Core modules (fs, http, etc.)
  2. Local files (./module, ../module)
  3. node_modules directory
  4. Global modules (if installed globally)

require() Path Types:

  • Relative: require('./module') or require('../module')
  • Absolute: require('/path/to/module')
  • Module Name: require('express') - searches node_modules