Skip to content

Latest commit

 

History

History
279 lines (217 loc) · 9.66 KB

File metadata and controls

279 lines (217 loc) · 9.66 KB

Node.js Crash Course

Disclaimer: This is a personal summary and interpretation based on a YouTube video. It is not official material and not endorsed by the original creator. All rights remain with the respective creators.

This document summarizes the key takeaways from the video. I highly recommend watching the full video for visual context and coding demonstrations.

Before You Get Started

  • I summarize key points to help you learn and review quickly.
  • Simply click on Ask AI links to dive into any topic you want.

AI-Powered buttons

Teach Me: 5 Years Old | Beginner | Intermediate | Advanced | (reset auto redirect)

Learn Differently: Analogy | Storytelling | Cheatsheet | Mindmap | Flashcards | Practical Projects | Code Examples | Common Mistakes

Check Understanding: Generate Quiz | Interview Me | Refactor Challenge | Assessment Rubric | Next Steps

What is Node.js?

Node.js is a JavaScript runtime built on Chrome’s V8 engine that lets you run JavaScript outside the browser — on your computer or on a server. It’s not a framework or a language, just an environment that gives JavaScript access to the file system, network, and other OS features.

Used mainly for server-side apps, APIs, microservices, real-time apps (chat, games), CLI tools, scraping, etc. Huge companies (Netflix, Uber, LinkedIn) and startups love it because it’s fast, scalable, and shares the same language (JavaScript) across front-end and back-end.

Ask AI: What is Node.js

How Node.js Works (Event Loop & Non-Blocking I/O)

Node.js is single-threaded but non-blocking. Instead of waiting for I/O (file reads, DB queries, network requests), it hands the task to the system kernel and keeps running. When the operation finishes, a callback is pushed to the event queue, and the event loop picks it up.

This architecture makes Node extremely efficient for I/O-heavy workloads and capable of handling thousands of concurrent connections with very little overhead.

Ask AI: Node.js Event Loop

Installation & First Steps

Download the LTS version from nodejs.org → run the installer → you’re done.
Check with:

node --version
npm --version

Node comes with a REPL (just type node in terminal) — great for quick experiments.

Ask AI: Installing Node.js

Project Setup & package.json

mkdir my-project && cd my-project
npm init -y          # creates package.json

Main fields you’ll touch:

  • "type": "module" → enables ES modules (import/export syntax)
  • "scripts" → custom commands ("start": "node server.js")

Ask AI: package.json in Node.js

Modules – CommonJS vs ESM

CommonJS (default, older):

// math.js
module.exports = { add, subtract };

// index.js
const { add } = require('./math');

ESM (modern, recommended):

// math.js
export const add = (a, b) => a + b;

// index.js
import { add } from './math.js';

Just add "type": "module" in package.json to use ESM.

Ask AI: ES Modules vs CommonJS

Creating a Basic HTTP Server (Core http Module)

import http from 'http';

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

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

Key objects:

  • req → url, method, headers
  • res → setHeader(), writeHead(), write(), end()

Ask AI: Node.js http createServer

Routing & Serving Static Files

Manually check req.url and req.method:

if (req.url === '/' && req.method === 'GET') {
  // serve index.html
}

Serving a real HTML file:

import fs from 'fs/promises';

const data = await fs.readFile(`./public${req.url === '/' ? '/index.html' : req.url}`);
res.setHeader('Content-Type', 'text/html');
res.end(data);

Ask AI: Serving static files with Node.js

Building a Simple REST API (Vanilla Node.js)

Example handlers:

if (req.url === '/api/users' && req.method === 'GET') {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(users));
}

Getting a single resource with regex:

const match = req.url.match(/^\/api\/users\/(\d+)$/);
if (match && req.method === 'GET') { ... }

Creating a resource (POST):

let body = '';
req.on('data', chunk => body += chunk.toString());
req.on('end', () => {
  const newUser = JSON.parse(body);
  users.push({ ...newUser, id: users.length + 1 });
  res.writeHead(201, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(newUser));
});

Ask AI: Build REST API with vanilla Node.js

Middleware Pattern

const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};

const jsonMiddleware = (req, res, next) => {
  res.setHeader('Content-Type', 'application/json');
  next();
};

server.on('request', (req, res) => {
  logger(req, res, () => {
    jsonMiddleware(req, res, () => {
      // routing logic here
    });
  });
});

Ask AI: Middleware in vanilla Node.js

Nodemon & Environment Variables

npm i -D nodemon

package.json script:

"scripts": {
  "start": "nodemon server.js",
  "dev": "node --env-file=.env server.js"
}

Ask AI: Nodemon and .env files

Core Modules Quick Overview

fs (File System)

import fs from 'fs/promises';

await fs.writeFile('test.txt', 'Hello');      // overwrites
await fs.appendFile('test.txt', '\nWorld');   // appends
const data = await fs.readFile('test.txt', 'utf8');

path

import path from 'path';

path.basename('/users/ali/file.txt')  // → 'file.txt'
path.extname('/users/ali/file.txt')    '.txt'
path.join(__dirname, 'public', 'index.html')

os

import os from 'os';

os.totalmem()    bytes
os.freemem()
os.cpus()        array of core info

url

import { URL } from 'url';

const myUrl = new URL('https://example.com:8000/path?name=ali#section');
myUrl.searchParams.get('name')  'ali'

crypto (hashing example)

import { createHash } from 'crypto';

const hash = createHash('sha256')
  .update('password123')
  .digest('hex');

events

import { EventEmitter } from 'events';

const emitter = new EventEmitter();

emitter.on('greet', (name) => console.log(`Hello ${name}`));
emitter.emit('greet', 'Ali');

process

process.env.PORT
process.argv      command-line arguments
process.cwd()     current working directory
process.exit(0)   exit with success

About the summarizer

I'm Ali Sol, a Backend Developer. Learn more: