Module 1: Node.js Fundamentals

Learn Node.js fundamentals including event loop, asynchronous programming, modules, and file system operations.

Back to Course|3 hours|Beginner

Node.js Fundamentals

Learn Node.js fundamentals including event loop, asynchronous programming, modules, and file system operations.

Progress: 0/4 topics completed0%

Select Topics Overview

What is Node.js?

Understanding Node.js architecture, runtime environment, and its role in modern web development

Content by: Umesh Dangar

MERN Stack Developer

Connect

Introduction to Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server-side, enabling full-stack JavaScript development. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Node.js Architecture

  • V8 JavaScript Engine - Chrome's high-performance JavaScript engine
  • Event Loop - Handles asynchronous operations efficiently
  • Libuv - Cross-platform asynchronous I/O library
  • Core Modules - Built-in modules for common functionality
  • NPM - Node Package Manager for dependency management

Node.js vs Other Technologies

  • vs PHP: Node.js is faster for I/O operations and real-time applications
  • vs Python: Better performance for web applications, single language for full-stack
  • vs Java: Lighter weight, faster development cycle, better for microservices
  • vs .NET: Cross-platform, open-source, better for real-time applications
  • vs Ruby: Better performance, larger ecosystem, more scalable

Node.js Use Cases

  • Web Applications: REST APIs, real-time applications, microservices
  • Real-time Applications: Chat applications, gaming servers, live streaming
  • Command Line Tools: Build tools, automation scripts, development utilities
  • Desktop Applications: Using Electron for cross-platform desktop apps
  • IoT Applications: Server-side logic for Internet of Things devices
  • Proxy Servers: API gateways, load balancers, reverse proxies

Basic Node.js Setup

Code Example
// Check Node.js version
node --version

// Check NPM version
npm --version

// Create a new Node.js project
mkdir my-node-app
cd my-node-app
npm init -y

// Install dependencies
npm install express

// Basic Node.js server
const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World!');
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});
Swipe to see more code

Node.js Development Environment

Code Example
// Essential development tools for Node.js
// 1. Node Version Manager (NVM)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 18
nvm use 18

// 2. Package.json configuration
{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "A Node.js application",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest"
  },
  "keywords": ["nodejs", "javascript"],
  "author": "Your Name",
  "license": "MIT"
}

// 3. Essential NPM packages
npm install express cors helmet morgan
npm install --save-dev nodemon jest supertest

// 4. Environment configuration
// .env file
PORT=3000
NODE_ENV=development
DATABASE_URL=mongodb://localhost:27017/myapp

// Load environment variables
require('dotenv').config();
Swipe to see more code

Mini-Project: Hello World Server

Code Example
// Create a comprehensive Hello World server with multiple endpoints
const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const path = parsedUrl.pathname;
    const method = req.method;
    
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Content-Type', 'application/json');
    
    // Route handling
    if (path === '/' && method === 'GET') {
        res.writeHead(200);
        res.end(JSON.stringify({
            message: 'Hello World!',
            timestamp: new Date().toISOString(),
            method: method,
            path: path
        }));
    } else if (path === '/health' && method === 'GET') {
        res.writeHead(200);
        res.end(JSON.stringify({
            status: 'healthy',
            uptime: process.uptime(),
            memory: process.memoryUsage()
        }));
    } else if (path === '/echo' && method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            res.writeHead(200);
            res.end(JSON.stringify({
                message: 'Echo response',
                received: body,
                timestamp: new Date().toISOString()
            }));
        });
    } else {
        res.writeHead(404);
        res.end(JSON.stringify({
            error: 'Not Found',
            message: 'The requested resource was not found'
        }));
    }
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
    console.log('Available endpoints:');
    console.log('  GET  / - Hello World');
    console.log('  GET  /health - Health check');
    console.log('  POST /echo - Echo back request body');
});

// Graceful shutdown
process.on('SIGTERM', () => {
    console.log('SIGTERM received, shutting down gracefully');
    server.close(() => {
        console.log('Process terminated');
    });
});
Swipe to see more code

🎯 Practice Exercise

Test your understanding of this topic:

Additional Resources

📚 Recommended Reading

  • Node.js Official Documentation
  • Understanding the Node.js Event Loop
  • Node.js Module System Guide

🌐 Online Resources

  • Node.js Tutorial for Beginners
  • Asynchronous JavaScript Patterns
  • NPM Package Management Guide

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 2