2️⃣ Node.js Fundamentals

Understanding the JavaScript Runtime

2.1 What is Node.js?

Node.js is a JavaScript runtime that lets you run JavaScript code outside of a web browser - on your computer or server.

┌─────────────────────────────────────────────────────────────┐ │ Before Node.js │ │ │ │ JavaScript ──► Browser Only (Chrome, Firefox, etc.) │ │ │ ├─────────────────────────────────────────────────────────────┤ │ With Node.js │ │ │ │ JavaScript ──► Browser (Frontend) │ │ ──► Server (Backend) │ │ ──► Desktop Apps (Electron) │ │ ──► Command Line Tools │ └─────────────────────────────────────────────────────────────┘

Key Characteristics

1. JavaScript Runtime

Node.js uses the same V8 engine that powers Google Chrome. Your JavaScript runs directly on the machine.

2. Single-Threaded

Node uses one thread to handle all requests. But don't worry - it's very efficient!

3. Non-Blocking I/O

Node doesn't wait for slow operations (file reading, database queries). It continues processing other requests.

💡 Why is Node Popular for APIs?
  • ⚡ Fast - V8 engine is highly optimized
  • 🔄 Same Language - JavaScript for frontend AND backend
  • 📦 NPM - Largest package ecosystem (1M+ packages)
  • 🌐 Great for Real-time - Chat apps, live updates

Setup & First Script

Step 1: Install Node.js

1 Download from nodejs.org (choose LTS version)
2 Run the installer and follow the prompts
3 Verify installation in terminal:
# Check Node.js version
node --version
# Output: v20.10.0 (or similar)

# Check npm version
npm --version
# Output: 10.2.0 (or similar)

Step 2: Create Your First Script

Create a file called hello.js:

// hello.js - Your first Node.js program

console.log("Hello from Node.js!");

const message = "Node runs JavaScript outside the browser";
console.log(message);

// Node can access system information
console.log("Platform:", process.platform);     // win32, darwin, linux
console.log("Node Version:", process.version);   // v20.10.0
console.log("Current Directory:", process.cwd()); // Working directory

Run it in terminal:

node hello.js

Output:

Hello from Node.js!
Node runs JavaScript outside the browser
Platform: win32
Node Version: v20.10.0
Current Directory: C:\Users\yourname\projects
🎉 Congratulations! You just ran JavaScript without a browser!

2.2 Node Core Modules

Node comes with built-in modules. No installation needed - just require() them!

🟢 The http Module

Create web servers:

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

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

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

Run and visit http://localhost:3000 in your browser!

🟢 The fs Module (File System)

Read and write files:

// files.js - Working with files
const fs = require('fs');

// ✍️ Write a file (synchronous)
fs.writeFileSync('message.txt', 'Hello from Node!');
console.log('File created!');

// 📖 Read a file (synchronous)
const content = fs.readFileSync('message.txt', 'utf8');
console.log('File content:', content);

// 📋 List files in directory
const files = fs.readdirSync('.');
console.log('Files in directory:', files);

// ❓ Check if file exists
if (fs.existsSync('message.txt')) {
  console.log('File exists!');
}

🟢 The path Module

Handle file paths safely across operating systems:

// paths.js - Working with paths
const path = require('path');

// Join paths (works on Windows, Mac, Linux)
const filePath = path.join(__dirname, 'data', 'users.json');
console.log('Full path:', filePath);
// Windows: C:\project\data\users.json
// Mac/Linux: /project/data/users.json

// Get file extension
console.log(path.extname('photo.jpg'));      // .jpg
console.log(path.extname('document.pdf'));  // .pdf

// Get filename without path
console.log(path.basename('/users/data/file.txt'));  // file.txt

// Get directory name
console.log(path.dirname('/users/data/file.txt'));   // /users/data

// Special variables
console.log('Current file:', __filename);  // Full path to this file
console.log('Current dir:', __dirname);    // Directory of this file
⚠️ Important: Always use path.join() instead of string concatenation for paths. It handles Windows backslashes and Unix forward slashes automatically!

Simple HTTP Server Demo (Serving JSON)

This is what React's fetch() connects to:

// api-server.js - A simple JSON API
const http = require('http');

// Sample data
const products = [
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Phone', price: 699 },
  { id: 3, name: 'Tablet', price: 499 }
];

const server = http.createServer((req, res) => {
  // Set JSON headers
  res.writeHead(200, { 
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'  // Allow React to connect
  });
  
  // Send JSON response
  res.end(JSON.stringify(products));
});

server.listen(3000, () => {
  console.log('API running at http://localhost:3000');
  console.log('Try visiting it in your browser!');
});

Testing Your API

  1. Run node api-server.js
  2. Open http://localhost:3000 in browser
  3. You'll see the JSON array of products!

Module Summary

Module Purpose Common Methods
http Create web servers createServer(), listen()
fs File operations readFile(), writeFile(), readdir()
path Path manipulation join(), basename(), extname()
os Operating system info platform(), cpus(), totalmem()
events Event handling on(), emit()
🎯 Key Takeaways:
  • Node.js = JavaScript running on your computer/server
  • Use require() to import modules
  • Built-in modules: http, fs, path (no install needed)
  • http module creates servers that serve JSON to React