01How The Internet Works 02Your First Node.js Server 03HTTP Methods and JSON 04Express.js Framework 05Building REST APIs 06MongoDB Fundamentals 07Mongoose ODM 08Data Modeling 09Authentication Basics 10JWT Implementation

Settings

Theme
Sand
Cloud
Midnight
Forest
Sunset
Purple
Ocean
Crimson
Font
Merriweather
Inter
JetBrains
Space Grotesk
Fira Code
Playfair
Font Size
100%
Bookmark
No bookmark set
Day 2

Your First Node.js Server

Today we move from theory to practice. You will install Node.js, understand how it works, and build a working web server from scratch - no frameworks, just pure Node.js.

What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 engine. It lets you run JavaScript outside the browser - on your computer, on servers, anywhere. Before Node.js, JavaScript could only run in browsers.

Real World Analogy

JavaScript in a browser is like a chef who can only work in one specific restaurant kitchen. Node.js is like giving that chef their own portable kitchen - now they can cook anywhere, not just in that one restaurant.

Why Node.js for Backend?

  • Same Language - Use JavaScript for both frontend and backend
  • Non-blocking I/O - Handles thousands of concurrent connections efficiently
  • NPM Ecosystem - Over 2 million packages available
  • Fast Execution - V8 engine compiles JavaScript to machine code
  • Active Community - Huge community, tons of resources and jobs

Installing Node.js

Download Node.js from nodejs.org. Choose the LTS (Long Term Support) version for stability.

Verify Installation
# Check Node.js version
node --version
# Output: v20.x.x (or similar)

# Check npm version (Node Package Manager - comes with Node)
npm --version
# Output: 10.x.x (or similar)

# Run JavaScript in terminal (REPL mode)
node
> console.log("Hello from Node!")
Hello from Node!
> .exit

Your First Node.js File

Create a new folder for your project and create a file called app.js:

app.js
// This runs on your computer, NOT in a browser
console.log("Hello from Node.js!");

// Node has access to things browsers don't
console.log("Current directory:", __dirname);
console.log("Current file:", __filename);
console.log("Process ID:", process.pid);
console.log("Node version:", process.version);
Terminal
# Run the file with node
node app.js

# Output:
Hello from Node.js!
Current directory: /Users/you/myproject
Current file: /Users/you/myproject/app.js
Process ID: 12345
Node version: v20.10.0

Understanding Modules

Node.js organizes code into modules. There are three types:

Types of Modules

  • Core Modules - Built into Node.js (http, fs, path, os)
  • Local Modules - Files you create in your project
  • Third-party Modules - Installed via npm (express, lodash)
Using Core Modules
// Import core modules using require()
const os = require('os');        // Operating system info
const path = require('path');    // File path utilities
const fs = require('fs');        // File system operations

// OS module examples
console.log("Platform:", os.platform());     // darwin, win32, linux
console.log("CPU Cores:", os.cpus().length);
console.log("Free Memory:", os.freemem() / 1024 / 1024, "MB");
console.log("Home Directory:", os.homedir());

// Path module examples
const filePath = '/users/john/documents/file.txt';
console.log("Directory:", path.dirname(filePath));   // /users/john/documents
console.log("Filename:", path.basename(filePath));   // file.txt
console.log("Extension:", path.extname(filePath));   // .txt

// Join paths safely (handles / vs \ across OS)
const fullPath = path.join(__dirname, 'data', 'users.json');
console.log("Full path:", fullPath);

Creating Your Own Modules

math.js - Your custom module
// Define functions in this module
function add(a, b) {
    return a + b;
}

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

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

// Export what you want other files to access
module.exports = {
    add,
    subtract,
    multiply
};

// Alternative: export individually
// module.exports.add = add;
// module.exports.subtract = subtract;
app.js - Using your module
// Import your custom module (use ./ for local files)
const math = require('./math');

console.log(math.add(5, 3));       // 8
console.log(math.subtract(10, 4)); // 6
console.log(math.multiply(3, 7));  // 21

// Or use destructuring
const { add, multiply } = require('./math');
console.log(add(2, 2));  // 4

The HTTP Module - Building a Server

Now for the main event - creating a web server. Node.js has a built-in http module for this:

server.js - Basic HTTP Server
// Import the http module
const http = require('http');

// Create a server that handles incoming requests
// The callback runs for EVERY incoming request
const server = http.createServer((req, res) => {
    // req = information about the incoming request
    // res = object we use to send back a response

    // Log every request that comes in
    console.log(`Request: ${req.method} ${req.url}`);

    // Set the response status code and headers
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');

    // Send the response body and end the response
    res.end('Hello, World!');
});

// Start listening for requests on port 3000
const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});
Terminal
# Start the server
node server.js
# Output: Server running at http://localhost:3000/

# Open http://localhost:3000 in your browser
# You'll see "Hello, World!"

# Press Ctrl+C to stop the server
Key Insight

The server keeps running until you stop it. It sits there waiting for requests. Every time someone visits your URL, the callback function runs. This is the foundation of all backend development.

Understanding Request and Response

Let us explore the req and res objects more deeply:

Examining the Request Object
const http = require('http');

const server = http.createServer((req, res) => {
    // Request method: GET, POST, PUT, DELETE, etc.
    console.log('Method:', req.method);

    // The URL path requested
    console.log('URL:', req.url);

    // Request headers (metadata)
    console.log('Headers:', req.headers);

    // Useful headers
    console.log('User-Agent:', req.headers['user-agent']);
    console.log('Host:', req.headers.host);

    res.end('Check your terminal for request details!');
});

server.listen(3000);

Routing - Different Responses for Different URLs

A real server needs to respond differently based on the URL. This is called routing:

server.js - Basic Routing
const http = require('http');

const server = http.createServer((req, res) => {
    // Get the URL path
    const url = req.url;
    const method = req.method;

    // Route: Home page
    if (url === '/' && method === 'GET') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end('<h1>Welcome to the Home Page</h1>');
    }
    // Route: About page
    else if (url === '/about' && method === 'GET') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end('<h1>About Us</h1><p>We are learning Node.js!</p>');
    }
    // Route: API endpoint
    else if (url === '/api/data' && method === 'GET') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        const data = {
            message: 'Hello from the API!',
            timestamp: new Date().toISOString()
        };
        res.end(JSON.stringify(data));
    }
    // Route: 404 Not Found (no matching route)
    else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/html');
        res.end('<h1>404 - Page Not Found</h1>');
    }
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log('Try visiting:');
    console.log('  http://localhost:3000/');
    console.log('  http://localhost:3000/about');
    console.log('  http://localhost:3000/api/data');
    console.log('  http://localhost:3000/random (404)');
});

Serving HTML Files

Instead of writing HTML in strings, let us serve actual HTML files:

index.html
<!DOCTYPE html>
<html>
<head>
    <title>My Node.js Site</title>
</head>
<body>
    <h1>Welcome!</h1>
    <p>This page is served by Node.js</p>
</body>
</html>
server.js - Serving HTML Files
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        // Build the path to index.html
        const filePath = path.join(__dirname, 'index.html');

        // Read the file from disk
        fs.readFile(filePath, (err, content) => {
            if (err) {
                // Error reading file
                res.statusCode = 500;
                res.end('Server Error');
                return;
            }

            // Successfully read file - send it
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.end(content);
        });
    } else {
        res.statusCode = 404;
        res.end('Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

NPM - Node Package Manager

NPM lets you install and manage third-party packages. Let us set up a proper project:

Terminal - Project Setup
# Create a new folder and navigate into it
mkdir my-server
cd my-server

# Initialize a new npm project
# -y accepts all defaults
npm init -y

# This creates package.json - your project's config file
package.json
{
  "name": "my-server",
  "version": "1.0.0",
  "description": "My first Node.js server",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "dev": "node --watch server.js"  // Auto-restart on changes
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Running Your Server
# Run using npm scripts
npm start       # Runs: node server.js
npm run dev     # Runs with auto-restart on file changes

Video Resources

Mini Project

Build a Personal Info Server

Create a server with these routes:

  • GET / - Return an HTML page with your name
  • GET /about - Return JSON with info about you (name, hobby, etc.)
  • GET /time - Return the current date and time as JSON
  • GET /random - Return a random number between 1-100
  • Any other URL returns a 404 page

Knowledge Check: Day 2

1. What does require() do in Node.js?

ACreates a new file
BImports a module so you can use its code
CRuns a server
DConnects to a database

2. What does res.end() do in an HTTP server?

AStops the server from running
BDeletes the response object
CSends the response body and signals the response is complete
DCloses the client's browser

3. How do you export a function from a Node.js module?

Amodule.exports = myFunction
Bexport myFunction
Creturn myFunction
Dpublic myFunction

Day 2 Complete!

You have built your first Node.js server! You understand modules, the http module, routing, and how to serve different content types. This is the foundation everything else builds upon.

Tomorrow, we dive deeper into HTTP methods (GET, POST, PUT, DELETE) and learn about JSON - the language APIs speak.