🔥Git and GitHub
🌼 Hello dear campers! 🌼
First of all, Happy Meskel! 🕯️🔥
I hope you enjoy the holiday with your family, and fill your hearts with joy. 🎉
Today, instead of JavaScript, we’re going to take a small but very important step into the real developer’s world:
👉 Learning Git and GitHub
This lesson is not about writing new code but about learning how to save, protect, and share the code you’ve already written.
Think of Git like a magical diary for your code: every time you make changes, Git takes a “snapshot” so you can always go back in time if something breaks.
And GitHub is like a giant library in the cloud where you can store your snapshots and share them with others — or even future employers 👀.
🔹 Step 1: Install Git
➤Go to git-scm.com
➤Download Git for your system (Windows/Mac/Linux).
➤During installation, keep pressing Next — the defaults are fine.
✅ After installing,
➤Open your project folder
Example: Calculator project.
➤ Right click inside the folder → choose Git Bash Here (if you installed Git) or
open your terminal/command prompt and type:
If it shows something like git version 2.xx.x → you’re ready! 🎉
🔹 Step 2: Create a GitHub Account
➤Go to github.com
➤Sign up with your email.
➤Pick a cool username (this will be part of your developer identity, so choose wisely 😉).
🔹 Step 3: Set Up Git on Your Computer
➤Open your terminal and introduce yourself to Git:
Now Git knows who you are whenever you make a “snapshot.”
🔹 Step 4: Initialize a Local Repo
Let’s say you have your Calculator project in a folder.
Go inside that folder using the terminal:
Then type:
This means: “Hey Git, start watching this folder for changes.”
🔹 Step 5: Take Your First Snapshot
➤git add . → prepare all files for the snapshot
➤git commit -m "..." → take the snapshot and give it a message
🔹 Step 6: Create a GitHub Repo
➤Go to GitHub → click New Repository
➤Name it something like calculator-project
➤Leave other options as default → click Create Repository
🔹 Step 7: Push Your Code to GitHub 🚀
Copy the commands GitHub gives you (something like this):
✅ Now refresh your GitHub repo page — BOOM! Your project is online 🎉
🔹 Step 8: live demo
Since pushing only the code to GitHub feels boring — let's show off our project in action. there are simple ways to make a live demo right from GitHub 🚀
Here are 2 showcase methods:
🔹 1. GitHub Pages (Best for HTML/CSS/JS projects)
This lets your project run live in the browser.
Steps (after pushing code):
Go to your repo → Settings.
Scroll to Pages.
Under Branch, select main → /root.
Save → you’ll get a live URL like:
👉 https://username.github.io/project-name/
Now anyone can click and see your calculator, clock, or quiz game in action!
🔹 2. Netlify / Vercel (One-click deploys)
Even easier:
Go to netlify.com (or vercel.com) → Sign in with GitHub.
Click “New Site” → choose your GitHub repo.
Deploy → boom 💥 live link in seconds.
✨ This way, you don’t just say:
“I made a calculator”
but proudly share:
👉 “Try my calculator live here: [link]”
🔹 Step 9: Do This for All Projects You Made
Push your:
🧮 Calculator
⏰ Digital Clock
❓ Quiz Game
…and more as we go along. That way, you’ll have a public portfolio of everything you build in this camp.
💡 Why This Is Important
➤If your laptop crashes, your code is safe.
➤You can show your GitHub to future job interviews.
➤You’ll feel like a real dev seeing your projects online 🌍.
You’re not just learning how to code — you’re learning how to be developers.
💥So go ahead:
👉 Install Git
👉 Create GitHub
👉 Push your projects
👉 then share your GitHub links in our group! Let’s celebrate each other’s progress 🎉
👉 invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
🌼 Hello dear campers! 🌼
First of all, Happy Meskel! 🕯️🔥
I hope you enjoy the holiday with your family, and fill your hearts with joy. 🎉
Today, instead of JavaScript, we’re going to take a small but very important step into the real developer’s world:
👉 Learning Git and GitHub
This lesson is not about writing new code but about learning how to save, protect, and share the code you’ve already written.
Think of Git like a magical diary for your code: every time you make changes, Git takes a “snapshot” so you can always go back in time if something breaks.
And GitHub is like a giant library in the cloud where you can store your snapshots and share them with others — or even future employers 👀.
🔹 Step 1: Install Git
➤Go to git-scm.com
➤Download Git for your system (Windows/Mac/Linux).
➤During installation, keep pressing Next — the defaults are fine.
✅ After installing,
➤Open your project folder
Example: Calculator project.
➤ Right click inside the folder → choose Git Bash Here (if you installed Git) or
open your terminal/command prompt and type:
git --version If it shows something like git version 2.xx.x → you’re ready! 🎉
🔹 Step 2: Create a GitHub Account
➤Go to github.com
➤Sign up with your email.
➤Pick a cool username (this will be part of your developer identity, so choose wisely 😉).
🔹 Step 3: Set Up Git on Your Computer
➤Open your terminal and introduce yourself to Git:
git config --global user.name "Your Name"
git config --global user.email "your@email.com" Now Git knows who you are whenever you make a “snapshot.”
🔹 Step 4: Initialize a Local Repo
Let’s say you have your Calculator project in a folder.
Go inside that folder using the terminal:
cd path/to/Calculator Then type:
git init This means: “Hey Git, start watching this folder for changes.”
🔹 Step 5: Take Your First Snapshot
git add .
git commit -m "First commit: my calculator project" ➤git add . → prepare all files for the snapshot
➤git commit -m "..." → take the snapshot and give it a message
🔹 Step 6: Create a GitHub Repo
➤Go to GitHub → click New Repository
➤Name it something like calculator-project
➤Leave other options as default → click Create Repository
🔹 Step 7: Push Your Code to GitHub 🚀
Copy the commands GitHub gives you (something like this):
git remote add origin https://github.com/username/calculator-project.git
git branch -M main
git push -u origin main
✅ Now refresh your GitHub repo page — BOOM! Your project is online 🎉
🔹 Step 8: live demo
Since pushing only the code to GitHub feels boring — let's show off our project in action. there are simple ways to make a live demo right from GitHub 🚀
Here are 2 showcase methods:
🔹 1. GitHub Pages (Best for HTML/CSS/JS projects)
This lets your project run live in the browser.
Steps (after pushing code):
Go to your repo → Settings.
Scroll to Pages.
Under Branch, select main → /root.
Save → you’ll get a live URL like:
👉 https://username.github.io/project-name/
Now anyone can click and see your calculator, clock, or quiz game in action!
🔹 2. Netlify / Vercel (One-click deploys)
Even easier:
Go to netlify.com (or vercel.com) → Sign in with GitHub.
Click “New Site” → choose your GitHub repo.
Deploy → boom 💥 live link in seconds.
✨ This way, you don’t just say:
“I made a calculator”
but proudly share:
👉 “Try my calculator live here: [link]”
🔹 Step 9: Do This for All Projects You Made
Push your:
🧮 Calculator
⏰ Digital Clock
❓ Quiz Game
…and more as we go along. That way, you’ll have a public portfolio of everything you build in this camp.
💡 Why This Is Important
➤If your laptop crashes, your code is safe.
➤You can show your GitHub to future job interviews.
➤You’ll feel like a real dev seeing your projects online 🌍.
You’re not just learning how to code — you’re learning how to be developers.
💥So go ahead:
👉 Install Git
👉 Create GitHub
👉 Push your projects
👉 then share your GitHub links in our group! Let’s celebrate each other’s progress 🎉
👉 invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
GitHub
GitHub · Change is constant. GitHub keeps you ahead.
Join the world's most widely adopted, AI-powered developer platform where millions of developers, businesses, and the largest open source community build software that advances humanity.
🔥2
Project 3: ProTask Board – A Drag-and-Drop Productivity App.
👋 Hello Campers!
I hope you’re all doing great 🌞 and coding with energy 💻.
Today’s challenge is ProTask Board – A Drag-and-Drop Productivity App.
This time, we’re not just making a simple to-do list. We’ll build something closer to a mini Trello/Notion where you can manage tasks, routines, and deadlines.
🎯 Core Features (must do)
➤Add Tasks → With title + description.
➤Sections → To Do, In Progress, Done.
➤Drag & Drop → Move tasks between sections.
➤Due dates & overdue highlighting.
➤Weekly & Monthly boards (switch between them).
✨ Optional Features (level up)
➤Custom sections (e.g., Work, Personal, Routines).
➤Task priority (Low/Medium/High with colors).
➤Recurring tasks (like daily routines).
➤Save all tasks in localStorage so they survive refresh.
💡 Hints
➤Store tasks in an array/object and re-render the UI from it.
➤Use ondragstart, ondragover, ondrop for drag and drop.
➤Save board state with JSON.stringify() to localStorage.
➤Generate unique IDs with Date.now().
⚠️ Common Pitfalls
➤Forgetting to give each column a unique ID.
➤Tasks disappearing after refresh → always save to localStorage.
➤Adding too many features at once → build step by step.
➤Cluttered design → keep UI clean and readable.
🛠️ Debugging Checklist
➤Can I add a task and see it in “To Do”?
➤Can I drag and drop tasks between columns?
➤Does refreshing the page restore my board?
➤Do priorities and due dates display correctly?
➤ Can I switch between Weekly and Monthly?
This project will push your skills to the next level 🚀. Start with the basics, then layer features one by one. Don’t rush—just enjoy building!
📤 Final Steps
When done:
💥 Push to GitHub ✅
💥 Deploy with GitHub Pages / Netlify 🌍
💥 Share your repo + live demo with us 🎉
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
👋 Hello Campers!
I hope you’re all doing great 🌞 and coding with energy 💻.
Today’s challenge is ProTask Board – A Drag-and-Drop Productivity App.
This time, we’re not just making a simple to-do list. We’ll build something closer to a mini Trello/Notion where you can manage tasks, routines, and deadlines.
🎯 Core Features (must do)
➤Add Tasks → With title + description.
➤Sections → To Do, In Progress, Done.
➤Drag & Drop → Move tasks between sections.
➤Due dates & overdue highlighting.
➤Weekly & Monthly boards (switch between them).
✨ Optional Features (level up)
➤Custom sections (e.g., Work, Personal, Routines).
➤Task priority (Low/Medium/High with colors).
➤Recurring tasks (like daily routines).
➤Save all tasks in localStorage so they survive refresh.
💡 Hints
➤Store tasks in an array/object and re-render the UI from it.
➤Use ondragstart, ondragover, ondrop for drag and drop.
➤Save board state with JSON.stringify() to localStorage.
➤Generate unique IDs with Date.now().
⚠️ Common Pitfalls
➤Forgetting to give each column a unique ID.
➤Tasks disappearing after refresh → always save to localStorage.
➤Adding too many features at once → build step by step.
➤Cluttered design → keep UI clean and readable.
🛠️ Debugging Checklist
➤Can I add a task and see it in “To Do”?
➤Can I drag and drop tasks between columns?
➤Does refreshing the page restore my board?
➤Do priorities and due dates display correctly?
➤ Can I switch between Weekly and Monthly?
This project will push your skills to the next level 🚀. Start with the basics, then layer features one by one. Don’t rush—just enjoy building!
📤 Final Steps
When done:
💥 Push to GitHub ✅
💥 Deploy with GitHub Pages / Netlify 🌍
💥 Share your repo + live demo with us 🎉
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
Project 4: Tvshow Database Browser 🎬🍿
👋 Hello Campers!
Hope you’re all doing well 🌞 and staying consistent with your code 💻✨.
Today we’re starting Project 4: Tvshow Database Browser 🎬🍿.
This is going to be a super fun one — you’ll practice APIs, fetch, DOM manipulation, and clean UI design, while building something that feels like a real-world app (think of a mini Netflix search tool).
🎯 Project Goal
➤➤Build a Tvshow Browser App where users can search for Tvshows and display details from a free API.
➤➤You’ll strengthen your skills with:
➥Fetching data from APIs
➥Handling JSON responses
➥DOM manipulation for displaying results
➥Error handling + clean UI
📋 Phase 1: Core Features (Must-Haves)
✅ Feature 1: Tvshow Search
➤Create a simple search bar with an input box + search button.
➤When the user types a Tvshow name and clicks search, fetch results from the API.
✅ Feature 2: Display Tvshow Results
Show at least:
➤Tvshow title 🎥
➤Release year 📅
➤Poster image 🖼️
➤Display results in a clean grid layout.
✅ Feature 3: Free API to Use
We’ll use the
When clicking a Tvshow card, fetch full details (plot, rating, genre) and display them.
🚀 Phase 2: Optional Features (Level Up)
➤Pagination: If results are more than 10, add "Next" and "Previous" buttons.
➤Loading Indicator: Show a spinner or “Loading…” text while fetching.
➤Error Handling: If no Tvshow is found, show a friendly “Tvshow not found 😢” message.
➤Favorites List: Add a "❤️ Save" button on each card, store favorites in localStorage.
💡 Little Hints
➤Always start by testing the API in your browser before coding.
➤Wrap your fetch() in try...catch to handle errors.
➤Structure your rendering code so it clears old results before showing new ones.
➤Use flexbox or CSS grid for neat Tvshow card layout.
⚠️ Common Pitfalls
➤Not handling empty searches → Always check if the input box is empty before fetching.
➤Unclear UI → Without images/posters, results look boring. Make sure your design is visually clean.
➤Blocking code → Don’t mix await fetch() with loops incorrectly; use for...of with await.
🛠️ Debugging Checklist
✅ Does the API URL open in your browser?
✅ Is the search input being read correctly in JS?
✅ Does console.log() show the fetched data before rendering?
✅ Are old results being cleared before new ones appear?
✅ Have you handled the case where no results are found?
📤 Final Steps
When you’re done building your Tvshow Browser App:
💥 Push to GitHub ✅
💥 Deploy with GitHub Pages / Netlify 🌍
💥 Share your repo + live demo with us 🎉
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
👋 Hello Campers!
Hope you’re all doing well 🌞 and staying consistent with your code 💻✨.
Today we’re starting Project 4: Tvshow Database Browser 🎬🍿.
This is going to be a super fun one — you’ll practice APIs, fetch, DOM manipulation, and clean UI design, while building something that feels like a real-world app (think of a mini Netflix search tool).
🎯 Project Goal
➤➤Build a Tvshow Browser App where users can search for Tvshows and display details from a free API.
➤➤You’ll strengthen your skills with:
➥Fetching data from APIs
➥Handling JSON responses
➥DOM manipulation for displaying results
➥Error handling + clean UI
📋 Phase 1: Core Features (Must-Haves)
✅ Feature 1: Tvshow Search
➤Create a simple search bar with an input box + search button.
➤When the user types a Tvshow name and clicks search, fetch results from the API.
✅ Feature 2: Display Tvshow Results
Show at least:
➤Tvshow title 🎥
➤Release year 📅
➤Poster image 🖼️
➤Display results in a clean grid layout.
✅ Feature 3: Free API to Use
We’ll use the
https://api.tvmaze.com/shows?page=0
✅ Feature 4: Tvshow Details Page: When clicking a Tvshow card, fetch full details (plot, rating, genre) and display them.
🚀 Phase 2: Optional Features (Level Up)
➤Pagination: If results are more than 10, add "Next" and "Previous" buttons.
➤Loading Indicator: Show a spinner or “Loading…” text while fetching.
➤Error Handling: If no Tvshow is found, show a friendly “Tvshow not found 😢” message.
➤Favorites List: Add a "❤️ Save" button on each card, store favorites in localStorage.
💡 Little Hints
➤Always start by testing the API in your browser before coding.
➤Wrap your fetch() in try...catch to handle errors.
➤Structure your rendering code so it clears old results before showing new ones.
➤Use flexbox or CSS grid for neat Tvshow card layout.
⚠️ Common Pitfalls
➤Not handling empty searches → Always check if the input box is empty before fetching.
➤Unclear UI → Without images/posters, results look boring. Make sure your design is visually clean.
➤Blocking code → Don’t mix await fetch() with loops incorrectly; use for...of with await.
🛠️ Debugging Checklist
✅ Does the API URL open in your browser?
✅ Is the search input being read correctly in JS?
✅ Does console.log() show the fetched data before rendering?
✅ Are old results being cleared before new ones appear?
✅ Have you handled the case where no results are found?
📤 Final Steps
When you’re done building your Tvshow Browser App:
💥 Push to GitHub ✅
💥 Deploy with GitHub Pages / Netlify 🌍
💥 Share your repo + live demo with us 🎉
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
👍1
Project 5: Mini Crypto Wallet App
👋 Hello Campers!
Hope you’re all well and coding strong 💻✨.
Time for Project 5: Mini Crypto Wallet — buy, sell & transfer fake coins 🪙💸
This project is a safe, fun way to practice state management, async (APIs), DOM, event handling, and localStorage. You’ll simulate a tiny wallet where users can view live prices, buy/sell a fake token with virtual balance, and transfer tokens to other users. Nothing real is exchanged — it’s all simulated for learning.
🎯 Project Goal
Build a small single-page app that:
➤shows live crypto prices,
➤lets a user buy/sell a fake token with virtual fiat balance,
➤lets users transfer token amounts to other simulated users,
➤persists wallet data in localStorage.
This teaches fetching APIs, updating a consistent JavaScript state, validating input, and saving state.
🧩 Core Features (must-have)
➤Dashboard / Balance
Show the user’s balances:
➥Fiat balance (e.g., USD) — start with a default, e.g., $10000.00.
➥Token balance (e.g., FAKECOIN) — start at 0.
➥Show current token price in USD (live from a free API).
➤Live Price Fetch
➥Use a free, no-key endpoint to fetch crypto price. Here is one.
➥Update price on demand (Refresh button)
➤Buy Token
➥Input: USD amount to spend OR token quantity to buy.
➥Convert using current price, check fiat balance, subtract fiat, add tokens.
➥Show transaction confirmation and update dashboard.
➤Sell Token
➥Input: token quantity to sell OR USD amount to receive.
➥Convert using current price, check token balance, subtract tokens, add fiat.
➥Show transaction confirmation and update dashboard.
➤Transfer Tokens (Simulated Users)
➥Simple input: recipient name/email (string) and token amount.
➥Deduct tokens from sender and record a transfer transaction in local history.
➤Persist State
Save balances + transaction history in localStorage so the wallet survives refresh.
✨ Optional / Advanced Features (level up)
➥Multiple Tokens — allow user to buy/sell more than one fake token (e.g., FAKECOIN, DOGECOIN).
➥User Accounts (local) — let users choose a username on the device and store wallets per username.
➥Simple Chart — show a small sparkline of price history in the session (store recent price points).
➥Holdings Value — show portfolio total in USD = fiat + (token balance × price).
➥Validation & Friendly Errors — warnings for insufficient funds, invalid input.
➥Pretty UI / Animations — success toasts, disabled buttons while processing, UX polish.
🛠 Little Hints (implementation tips)
➥Normalize numbers: use parseFloat and toFixed(2) for display.
➥Conversion helpers: create usdToToken(usd, price) and tokenToUsd(amount, price) functions.
➥Atomic updates: update state first, persist to localStorage, then update the UI.
➥Disable buttons while processing to avoid double transactions.
➥Transaction ID: use Date.now() or similar for unique transaction references.
➥Confirm transfers with a small modal (recipient + amount) before applying.
➥API wrapper: write a function async function fetchPrice(coinId) that returns price or throws on error.
⚠️ Common Pitfalls (and how to avoid)
➥Floating point precision: avoid comparing floats directly. Round only for display; keep internal math consistent.
➥Use cents for fiat (work in integer cents) or be careful with toFixed.
➥Not checking balances: always verify user has enough fiat/tokens before buy/sell/transfer.
➥localStorage shape mismatch: handle JSON.parse errors with try/catch.
➥API downtime: always handle network errors and provide a friendly error message and fallback (e.g., “price unavailable — try again”).
📤 Final Steps
When you’re done building your Crypto mini wallet App:
💥 Push to GitHub ✅
💥 Deploy with GitHub Pages / Netlify 🌍
💥 Share your repo + live demo with us 🎉
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
👋 Hello Campers!
Hope you’re all well and coding strong 💻✨.
Time for Project 5: Mini Crypto Wallet — buy, sell & transfer fake coins 🪙💸
This project is a safe, fun way to practice state management, async (APIs), DOM, event handling, and localStorage. You’ll simulate a tiny wallet where users can view live prices, buy/sell a fake token with virtual balance, and transfer tokens to other users. Nothing real is exchanged — it’s all simulated for learning.
🎯 Project Goal
Build a small single-page app that:
➤shows live crypto prices,
➤lets a user buy/sell a fake token with virtual fiat balance,
➤lets users transfer token amounts to other simulated users,
➤persists wallet data in localStorage.
This teaches fetching APIs, updating a consistent JavaScript state, validating input, and saving state.
🧩 Core Features (must-have)
➤Dashboard / Balance
Show the user’s balances:
➥Fiat balance (e.g., USD) — start with a default, e.g., $10000.00.
➥Token balance (e.g., FAKECOIN) — start at 0.
➥Show current token price in USD (live from a free API).
➤Live Price Fetch
➥Use a free, no-key endpoint to fetch crypto price. Here is one.
https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=50&page=1&sparkline=false
➥Update price on demand (Refresh button)
➤Buy Token
➥Input: USD amount to spend OR token quantity to buy.
➥Convert using current price, check fiat balance, subtract fiat, add tokens.
➥Show transaction confirmation and update dashboard.
➤Sell Token
➥Input: token quantity to sell OR USD amount to receive.
➥Convert using current price, check token balance, subtract tokens, add fiat.
➥Show transaction confirmation and update dashboard.
➤Transfer Tokens (Simulated Users)
➥Simple input: recipient name/email (string) and token amount.
➥Deduct tokens from sender and record a transfer transaction in local history.
➤Persist State
Save balances + transaction history in localStorage so the wallet survives refresh.
✨ Optional / Advanced Features (level up)
➥Multiple Tokens — allow user to buy/sell more than one fake token (e.g., FAKECOIN, DOGECOIN).
➥User Accounts (local) — let users choose a username on the device and store wallets per username.
➥Simple Chart — show a small sparkline of price history in the session (store recent price points).
➥Holdings Value — show portfolio total in USD = fiat + (token balance × price).
➥Validation & Friendly Errors — warnings for insufficient funds, invalid input.
➥Pretty UI / Animations — success toasts, disabled buttons while processing, UX polish.
🛠 Little Hints (implementation tips)
➥Normalize numbers: use parseFloat and toFixed(2) for display.
➥Conversion helpers: create usdToToken(usd, price) and tokenToUsd(amount, price) functions.
➥Atomic updates: update state first, persist to localStorage, then update the UI.
➥Disable buttons while processing to avoid double transactions.
➥Transaction ID: use Date.now() or similar for unique transaction references.
➥Confirm transfers with a small modal (recipient + amount) before applying.
➥API wrapper: write a function async function fetchPrice(coinId) that returns price or throws on error.
⚠️ Common Pitfalls (and how to avoid)
➥Floating point precision: avoid comparing floats directly. Round only for display; keep internal math consistent.
➥Use cents for fiat (work in integer cents) or be careful with toFixed.
➥Not checking balances: always verify user has enough fiat/tokens before buy/sell/transfer.
➥localStorage shape mismatch: handle JSON.parse errors with try/catch.
➥API downtime: always handle network errors and provide a friendly error message and fallback (e.g., “price unavailable — try again”).
📤 Final Steps
When you’re done building your Crypto mini wallet App:
💥 Push to GitHub ✅
💥 Deploy with GitHub Pages / Netlify 🌍
💥 Share your repo + live demo with us 🎉
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
WEEK 6 DAY 1 Web Servers
Welcome to Backend Development Week 🚀.
🌻 Hey my amazing campers!
I hope you’ve all been doing great, coding hard, and proudly showing off those awesome projects you built! 💪
You’ve come so far — from simple DOM magic to powerful API integrations — and now it’s time to level up... 🧠🔥
Get ready to step into the backend world — where servers live, data flows, and your code truly comes alive! 🚀
Let’s dive in together 💻✨
Up until now, we’ve been working on Frontend JavaScript — the part of the web that you can see and interact with directly in your browser. But now, it’s time to go behind the scenes where the real magic happens: the backend.
Before we dive into Node.js, let’s understand the foundation of the internet: Web Servers and Protocols.
Think of this lesson as learning how roads and traffic rules work before we start driving a car. 🚗💨
🌍 What is a Web Server?
Imagine you go to a restaurant 🍴:
➤You (the client) ask for food (like typing a website address).
➤The waiter (the server) listens to your request.
➤The waiter goes to the kitchen, prepares the food, and brings it back.
That’s exactly what happens when you open a website:
1. You (the client/browser) request a page.
2. The server (a computer somewhere in the world) receives the request.
3. It prepares the response (like an HTML page or some data).
4. The server sends it back to you.
👉 A web server is just a computer program that listens for requests and sends back responses.
📡 Protocols: The Rules of Communication
A protocol is just a set of rules for communication.
Think of it like languages: if you speak Amharic and your friend speaks English only, you can’t understand each other. Protocols make sure everyone follows the same rules.
Common Web Protocols:
➤HTTP (HyperText Transfer Protocol):
The most common rule set for communication between browsers and servers.
Example: http://example.com
➤HTTPS (HyperText Transfer Protocol Secure):
Same as HTTP, but with encryption 🔐.
It protects data from hackers while traveling between your browser and the server.
Example: https://example.com
➤TCP/IP (Transmission Control Protocol / Internet Protocol):
The foundation of the internet — like the roads where all cars (data packets) travel.
📨 Request & Response
Every time you type a website, two things happen:
1. Request → Your browser sends a request (like “Give me the home page”).
2. Response → The server sends something back (like HTML, CSS, JS, images).
👉 This back-and-forth is what makes the internet work.
Analogy: Think of sending a letter by post 📬:
➤You write a letter (request).
➤The postman delivers it to the correct address (server).
➤The receiver replies back (response).
🔐 Why HTTPS is Important
Imagine buying something online🛒:
➥With HTTP, your credit card info could be seen by anyone spying on the road.
➥With HTTPS, the data is encrypted, like a sealed envelope. Nobody can read it except the server.
➥That’s why modern websites must use HTTPS.
🛠 Quick Demo (Beginner Friendly)
You can try this without coding:
1. Open your browser.
2. Visit any site (like https://www.wikipedia.org).
3. Right click → Inspect → Go to Network Tab.
4. Refresh the page.
👉 You’ll see all the requests your browser made and the responses it got.
This is exactly what happens between your computer and the web server!
✅ Summary
➤A web server is a computer that listens to requests and sends responses.
➤Protocols are rules that ensure communication works properly.
➤HTTP = communication rules.
➤HTTPS = secure communication with encryption.
➤Everything on the web is request & response.
📌 Next step: now that we understand the roads (protocols) and traffic (servers), we’re ready to learn how Node.js lets us build our own little server 🚦.
In the meantime
💥invite your friends,
and as always —
💥stay well, stay curious, and stay coding ✌️
Welcome to Backend Development Week 🚀.
🌻 Hey my amazing campers!
I hope you’ve all been doing great, coding hard, and proudly showing off those awesome projects you built! 💪
You’ve come so far — from simple DOM magic to powerful API integrations — and now it’s time to level up... 🧠🔥
Get ready to step into the backend world — where servers live, data flows, and your code truly comes alive! 🚀
Let’s dive in together 💻✨
Up until now, we’ve been working on Frontend JavaScript — the part of the web that you can see and interact with directly in your browser. But now, it’s time to go behind the scenes where the real magic happens: the backend.
Before we dive into Node.js, let’s understand the foundation of the internet: Web Servers and Protocols.
Think of this lesson as learning how roads and traffic rules work before we start driving a car. 🚗💨
🌍 What is a Web Server?
Imagine you go to a restaurant 🍴:
➤You (the client) ask for food (like typing a website address).
➤The waiter (the server) listens to your request.
➤The waiter goes to the kitchen, prepares the food, and brings it back.
That’s exactly what happens when you open a website:
1. You (the client/browser) request a page.
2. The server (a computer somewhere in the world) receives the request.
3. It prepares the response (like an HTML page or some data).
4. The server sends it back to you.
👉 A web server is just a computer program that listens for requests and sends back responses.
📡 Protocols: The Rules of Communication
A protocol is just a set of rules for communication.
Think of it like languages: if you speak Amharic and your friend speaks English only, you can’t understand each other. Protocols make sure everyone follows the same rules.
Common Web Protocols:
➤HTTP (HyperText Transfer Protocol):
The most common rule set for communication between browsers and servers.
Example: http://example.com
➤HTTPS (HyperText Transfer Protocol Secure):
Same as HTTP, but with encryption 🔐.
It protects data from hackers while traveling between your browser and the server.
Example: https://example.com
➤TCP/IP (Transmission Control Protocol / Internet Protocol):
The foundation of the internet — like the roads where all cars (data packets) travel.
📨 Request & Response
Every time you type a website, two things happen:
1. Request → Your browser sends a request (like “Give me the home page”).
2. Response → The server sends something back (like HTML, CSS, JS, images).
👉 This back-and-forth is what makes the internet work.
Analogy: Think of sending a letter by post 📬:
➤You write a letter (request).
➤The postman delivers it to the correct address (server).
➤The receiver replies back (response).
🔐 Why HTTPS is Important
Imagine buying something online🛒:
➥With HTTP, your credit card info could be seen by anyone spying on the road.
➥With HTTPS, the data is encrypted, like a sealed envelope. Nobody can read it except the server.
➥That’s why modern websites must use HTTPS.
🛠 Quick Demo (Beginner Friendly)
You can try this without coding:
1. Open your browser.
2. Visit any site (like https://www.wikipedia.org).
3. Right click → Inspect → Go to Network Tab.
4. Refresh the page.
👉 You’ll see all the requests your browser made and the responses it got.
This is exactly what happens between your computer and the web server!
✅ Summary
➤A web server is a computer that listens to requests and sends responses.
➤Protocols are rules that ensure communication works properly.
➤HTTP = communication rules.
➤HTTPS = secure communication with encryption.
➤Everything on the web is request & response.
📌 Next step: now that we understand the roads (protocols) and traffic (servers), we’re ready to learn how Node.js lets us build our own little server 🚦.
In the meantime
💥invite your friends,
and as always —
💥stay well, stay curious, and stay coding ✌️
www.wikipedia.org
Wikipedia, the free encyclopedia
Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation.
Week 6 Day 2: Introduction to Node.js.
👋 Hello Campers!
Hope you’re coding strong 💻🔥 and enjoying the journey so far.
Last time we learned about web servers, HTTP, and HTTPS — the “roads and traffic rules” of the internet.
👉 Today, we’ll finally meet Node.js 🚀 — the tool that lets us build web servers and powerful apps using only JavaScript!
🌱 What is Node.js?
Think of JavaScript like a talented musician 🎸 who used to only perform on stage (the browser).
The browser is the stage 🎭.
JavaScript could only “play music” there.
But then Node.js came along, like giving the musician the ability to perform anywhere — in the streets, at a wedding, or on the radio 📻.
👉 With Node.js, JavaScript can now run outside the browser, on your computer or a server.
That means we can use JavaScript for backend programming (servers, databases, APIs, files, etc.) not just for frontend websites.
⚡ Why Node.js is Powerful
➤One Language Everywhere → You already know JavaScript. No need to learn another language for backend!
➤Fast → Built on Google’s V8 engine (the same that powers Chrome).
➤Handles Many Users at Once → Great for chat apps, real-time apps, APIs.
➤Huge Ecosystem → Thousands of free packages via npm (Node Package Manager).
🛠 Installing Node.js
Let’s get Node.js ready on your computer:
➤Go to official website:
👉 https://nodejs.org
➤Choose the LTS version (Long Term Support)
It’s stable and beginner-friendly.
Example: "LTS 20.x.x" (whatever is shown).
➤Download & Install (just click “Next, Next” like any other software).
Check Installation:
➣Open Command Prompt / Terminal.
Think of the terminal (or command prompt) as a window that lets you talk directly to your computer using text commands instead of buttons.
➤On Windows, it’s usually called:
Command Prompt (cmd) or PowerShell or Terminal (newer Windows 11)
➤On Mac or Linux, it’s called Terminal.
It looks like a black window where you type white text.
➙How to open the terminal
1. Click on the Start Menu (bottom-left corner).
2. Type: cmd or terminal
3. Press Enter — you’ll see a black window appear.
If you’re using VS Code, you can open a terminal inside it easily:
Click on "run" ➞ “Terminal” → “New Terminal” on the top menu.
Or use the shortcut:
Ctrl + `
Something like this will appear
C:\Users\YourName\Desktop\myproject.
If the last path isn't your current folder , type
➥Type:
➥Then type:
🎉 If you see versions for both, Node.js is installed!
🖥 First Taste of Node.js
Create a new file on your desktop:
Inside it, write:
Run it using Node:
Open terminal/command prompt.
Go to the file’s folder.
Type:
👉 You’ll see:
Boom 💥 you just ran JavaScript outside the browser!
🗂 What You Can Do with Node.js
With Node.js, we can:
➤Build web servers 🌍
➤Connect to databases 🗄️
➤Create APIs 📡
➤Handle files (read/write) 📁
➤Make real-time apps (chat, live updates) 💬
➤Even build desktop apps and tools
✅ Summary
➥Node.js lets JavaScript run outside the browser.
➥It’s perfect for backend programming and building servers.
➥We installed Node.js and tested it with a simple console.log.
➥From here, we’ll learn how to use Node.js to build servers, APIs, and more.
In the meantime
💥invite your friends,
and as always —
💥stay well, stay curious, and stay coding ✌️
👋 Hello Campers!
Hope you’re coding strong 💻🔥 and enjoying the journey so far.
Last time we learned about web servers, HTTP, and HTTPS — the “roads and traffic rules” of the internet.
👉 Today, we’ll finally meet Node.js 🚀 — the tool that lets us build web servers and powerful apps using only JavaScript!
🌱 What is Node.js?
Think of JavaScript like a talented musician 🎸 who used to only perform on stage (the browser).
The browser is the stage 🎭.
JavaScript could only “play music” there.
But then Node.js came along, like giving the musician the ability to perform anywhere — in the streets, at a wedding, or on the radio 📻.
👉 With Node.js, JavaScript can now run outside the browser, on your computer or a server.
That means we can use JavaScript for backend programming (servers, databases, APIs, files, etc.) not just for frontend websites.
⚡ Why Node.js is Powerful
➤One Language Everywhere → You already know JavaScript. No need to learn another language for backend!
➤Fast → Built on Google’s V8 engine (the same that powers Chrome).
➤Handles Many Users at Once → Great for chat apps, real-time apps, APIs.
➤Huge Ecosystem → Thousands of free packages via npm (Node Package Manager).
🛠 Installing Node.js
Let’s get Node.js ready on your computer:
➤Go to official website:
👉 https://nodejs.org
➤Choose the LTS version (Long Term Support)
It’s stable and beginner-friendly.
Example: "LTS 20.x.x" (whatever is shown).
➤Download & Install (just click “Next, Next” like any other software).
Check Installation:
➣Open Command Prompt / Terminal.
Think of the terminal (or command prompt) as a window that lets you talk directly to your computer using text commands instead of buttons.
➤On Windows, it’s usually called:
Command Prompt (cmd) or PowerShell or Terminal (newer Windows 11)
➤On Mac or Linux, it’s called Terminal.
It looks like a black window where you type white text.
➙How to open the terminal
1. Click on the Start Menu (bottom-left corner).
2. Type: cmd or terminal
3. Press Enter — you’ll see a black window appear.
If you’re using VS Code, you can open a terminal inside it easily:
Click on "run" ➞ “Terminal” → “New Terminal” on the top menu.
Or use the shortcut:
Ctrl + `
Something like this will appear
C:\Users\YourName\Desktop\myproject.
If the last path isn't your current folder , type
cd yourCurrentFolder
➥Type:
node -v 👉 This shows your Node.js version (like v20.11.0).➥Then type:
npm -v 👉 This shows your npm version (like 10.5.0).🎉 If you see versions for both, Node.js is installed!
🖥 First Taste of Node.js
Create a new file on your desktop:
hello.js Inside it, write:
console.log("Hello from Node.js 👋🚀"); Run it using Node:
Open terminal/command prompt.
Go to the file’s folder.
Type:
node hello.js 👉 You’ll see:
Hello from Node.js 👋🚀 Boom 💥 you just ran JavaScript outside the browser!
🗂 What You Can Do with Node.js
With Node.js, we can:
➤Build web servers 🌍
➤Connect to databases 🗄️
➤Create APIs 📡
➤Handle files (read/write) 📁
➤Make real-time apps (chat, live updates) 💬
➤Even build desktop apps and tools
✅ Summary
➥Node.js lets JavaScript run outside the browser.
➥It’s perfect for backend programming and building servers.
➥We installed Node.js and tested it with a simple console.log.
➥From here, we’ll learn how to use Node.js to build servers, APIs, and more.
In the meantime
💥invite your friends,
and as always —
💥stay well, stay curious, and stay coding ✌️
nodejs.org
Node.js — Run JavaScript Everywhere
Node.js® is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.
❤1
Week 6 Day 3 Nodejs lesson
👋 Hello Campers!
Hey hey, brilliant coders! 💪✨
Hope you’ve been doing great, coding hard on your projects, and feeling proud of how far you’ve come. We’ve now opened the doors to the Backend World — and guess what? You’re officially learning how things work behind the scenes on the web! 🚀
Before we start building cool servers, let’s explore the building blocks of Node.js — Modules.
🧩 What Are Modules in Node.js?
Imagine your code as a big house 🏠.
If you try to build everything in one huge room — bedroom, kitchen, and bathroom all together — it’ll get messy fast!
So instead, you divide it into rooms — each with a specific job.
That’s what modules do in Node.js.
A module is like a small room in your project, built for one purpose.
Each module can contain functions, variables, and objects that you can use elsewhere.
You can import and export modules, so different parts of your app can work together neatly.
This makes your code cleaner, reusable, and easier to debug.
💡 Three Types of Modules in Node.js
Node gives you three kinds of modules:
1️⃣ Core (Built-in) Modules
These come with Node itself — no need to install anything.
Examples:
➤fs (File System) → read/write files
➤http → create web servers
➤path → handle file paths
➤os → get system information
You can think of core modules as tools in Node’s toolbox 🧰 — always ready when you need them.
2️⃣ Local (Custom) Modules
These are the modules you create yourself!
Maybe you have a file that handles math functions, and you want to use those functions in another file.
You can simply export them from one file and import them into another.
🧠 Think of custom modules like mini recipes you write yourself and reuse across your project.
3️⃣ Third-party Modules
These are created by other developers and shared online via npm (Node Package Manager) — which is installed automatically when you install Node.
You can install them using the command line (example: npm install moment), and they make development faster since you don’t need to reinvent the wheel.
🛍️ Think of npm modules as ready-made groceries — you don’t grow the ingredients yourself, you just pick what you need and start cooking!
⚙️ Setting Up Before Using Modules
Before using any modules, make sure:
Node.js is installed.
✅ Run node -v and npm -v to check.
You have initialized a project (this creates a package.json file):
Once that’s done, you’re ready to use modules. 🎉
🔍 Let’s See a Module in Action — The os Module
Let’s start with a built-in one that’s easy and fun: the os module.
It gives you information about your computer (operating system).
Create a file called info.js, and add this:
Then run it in your terminal:
You’ll see something like:
🎉 Boom! You just used your first Node module!
🧠 What Just Happened?
We used the require() function — it’s how Node imports modules.
The variable os now holds all the tools that come with the os module.
Each os.something() gives you a specific piece of data.
👋 Hello Campers!
Hey hey, brilliant coders! 💪✨
Hope you’ve been doing great, coding hard on your projects, and feeling proud of how far you’ve come. We’ve now opened the doors to the Backend World — and guess what? You’re officially learning how things work behind the scenes on the web! 🚀
Before we start building cool servers, let’s explore the building blocks of Node.js — Modules.
🧩 What Are Modules in Node.js?
Imagine your code as a big house 🏠.
If you try to build everything in one huge room — bedroom, kitchen, and bathroom all together — it’ll get messy fast!
So instead, you divide it into rooms — each with a specific job.
That’s what modules do in Node.js.
A module is like a small room in your project, built for one purpose.
Each module can contain functions, variables, and objects that you can use elsewhere.
You can import and export modules, so different parts of your app can work together neatly.
This makes your code cleaner, reusable, and easier to debug.
💡 Three Types of Modules in Node.js
Node gives you three kinds of modules:
1️⃣ Core (Built-in) Modules
These come with Node itself — no need to install anything.
Examples:
➤fs (File System) → read/write files
➤http → create web servers
➤path → handle file paths
➤os → get system information
You can think of core modules as tools in Node’s toolbox 🧰 — always ready when you need them.
2️⃣ Local (Custom) Modules
These are the modules you create yourself!
Maybe you have a file that handles math functions, and you want to use those functions in another file.
You can simply export them from one file and import them into another.
🧠 Think of custom modules like mini recipes you write yourself and reuse across your project.
3️⃣ Third-party Modules
These are created by other developers and shared online via npm (Node Package Manager) — which is installed automatically when you install Node.
You can install them using the command line (example: npm install moment), and they make development faster since you don’t need to reinvent the wheel.
🛍️ Think of npm modules as ready-made groceries — you don’t grow the ingredients yourself, you just pick what you need and start cooking!
⚙️ Setting Up Before Using Modules
Before using any modules, make sure:
Node.js is installed.
✅ Run node -v and npm -v to check.
You have initialized a project (this creates a package.json file):
npm init -y
This tells Node, “Hey! This folder is a Node project,” and it keeps track of any packages you install later.Once that’s done, you’re ready to use modules. 🎉
🔍 Let’s See a Module in Action — The os Module
Let’s start with a built-in one that’s easy and fun: the os module.
It gives you information about your computer (operating system).
Create a file called info.js, and add this:
// Import the built-in 'os' module
const os = require("os");
// Print some system information
console.log("Operating System:", os.type());
console.log("Home Directory:", os.homedir());
console.log("System Uptime (in seconds):", os.uptime());
console.log("Total Memory:", os.totalmem());
console.log("Free Memory:", os.freemem()); Then run it in your terminal:
node info.js You’ll see something like:
Operating System: Linux Home
Directory: /home/camper System
Uptime (in seconds): 104593
Total Memory: 8192000000
Free Memory: 3256789000 🎉 Boom! You just used your first Node module!
🧠 What Just Happened?
We used the require() function — it’s how Node imports modules.
The variable os now holds all the tools that come with the os module.
Each os.something() gives you a specific piece of data.
🔥1
💬 Analogy Time
Imagine Node.js as a giant factory 🏭.
Each module is a mini machine that does one task — one might cut, another might paint, another might package.
When you require() a module, you’re saying,
🧰 Quick Look at a Custom Module
Let’s make one quickly so you get the idea.
In one file, math.js:
Then in app.js:
💡 See that? You created your own module and imported it — just like the professionals do.
⚠️ Common Pitfalls
❌ Forgetting the ./ when importing your own files (Node will look for a built-in module instead).
❌ Not exporting functions from your custom module — you’ll get “undefined.”
❌ Forgetting to run npm init -y — some npm packages won’t install properly without it.
❌ Mixing up file extensions — Node only understands .js by default.
🧭 Summary
✅ Modules help you organize and reuse code.
✅ Node has built-in modules like fs, path, os, and http.
✅ You can make your own custom modules and use them with require().
✅ Third-party modules can be installed from npm when you need extra features.
Until Next time , try these os BuiltIns and discover what they display:
➣os.type()
➣os.release()
➣os.platform()
➣os.arch()
➣os.uptime()
➣os.hostname()
➣os.userInfo()
➣os.totalmem()
➣os.freemem()
➣os.cpus()
➣os.networkInterfaces()
➣os.tmpdir()
➣os.homedir()
➣os.endianness()
In the meantime
💥invite your friends,
and as always —
💥stay well, stay curious, and stay coding ✌️
Imagine Node.js as a giant factory 🏭.
Each module is a mini machine that does one task — one might cut, another might paint, another might package.
When you require() a module, you’re saying,
“Hey Node, bring that mini machine here — I need its help!”
🧰 Quick Look at a Custom Module
Let’s make one quickly so you get the idea.
In one file, math.js:
function add(a, b) {
return a + b; }
function multiply(a, b) {
return a * b; }
// Export the functions
module.exports = { add, multiply }; Then in app.js:
const math = require("./math");
console.log(math.add(3, 5)); // 8
console.log(math.multiply(4, 6)); // 24 💡 See that? You created your own module and imported it — just like the professionals do.
⚠️ Common Pitfalls
❌ Forgetting the ./ when importing your own files (Node will look for a built-in module instead).
❌ Not exporting functions from your custom module — you’ll get “undefined.”
❌ Forgetting to run npm init -y — some npm packages won’t install properly without it.
❌ Mixing up file extensions — Node only understands .js by default.
🧭 Summary
✅ Modules help you organize and reuse code.
✅ Node has built-in modules like fs, path, os, and http.
✅ You can make your own custom modules and use them with require().
✅ Third-party modules can be installed from npm when you need extra features.
Until Next time , try these os BuiltIns and discover what they display:
➣os.type()
➣os.release()
➣os.platform()
➣os.arch()
➣os.uptime()
➣os.hostname()
➣os.userInfo()
➣os.totalmem()
➣os.freemem()
➣os.cpus()
➣os.networkInterfaces()
➣os.tmpdir()
➣os.homedir()
➣os.endianness()
In the meantime
💥invite your friends,
and as always —
💥stay well, stay curious, and stay coding ✌️
🔥1
Whenever you get curious or stuck — say, you wonder what else the os module can do — Node.js has its own official documentation where every built-in module, method, and example is explained clearly.
You can go there and search for “os” or any module name. You’ll see a list of all available methods, examples, and short descriptions straight from the source.
🔗 Check it out here:
https://nodejs.org/docs/latest/api/
⚡ Pro tip: Real developers refer to docs a lot. The goal isn’t to memorize everything, but to know where to look when you need something.
So… go explore a little today. Try finding something in the docs, use it in your code, and see what happens! That’s how you become unstoppable 🚀
You can go there and search for “os” or any module name. You’ll see a list of all available methods, examples, and short descriptions straight from the source.
🔗 Check it out here:
https://nodejs.org/docs/latest/api/
⚡ Pro tip: Real developers refer to docs a lot. The goal isn’t to memorize everything, but to know where to look when you need something.
So… go explore a little today. Try finding something in the docs, use it in your code, and see what happens! That’s how you become unstoppable 🚀
WEEK 6 DAY 4 Nodejs Lesson
👋 Hey Awesome Campers!
I hope you’ve all been doing great and still coding strong 💪🔥!
So today, we’re going to learn something super practical — how to work with the file system and paths in Node.js using two important built-in modules:
👉 fs (File System)
👉 path (Path Utilities)
🗂️ What Are Modules Again?
Remember last time, we said modules in Node.js are like tools in a big developer toolbox — each tool (module) helps you do a specific job.
Now, two of the most powerful tools in that box are:
➡️fs → helps you interact with files and folders.
➡️path → helps you safely build file paths (because paths can get messy).
🧰 The fs Module – File System
The fs module lets Node.js work with your computer’s file system.
With it, you can:
➙Read files
➙Create new files
➙Write or append data
➙Rename or delete files
Think of it like Node’s hands 👐 that can open, read, and write notes in your computer’s drawers (folders).
🔹 Step 1: Import the fs module
Every time you want to use it, you must import it:
🔹 Step 2: Reading a File
Let’s say we have a text file named message.txt that says:
We can read it using two methods:
➣Synchronous – waits for the file to finish reading before moving on.
➣Asynchronous – doesn’t wait (recommended for most cases).
✅ Example (Asynchronous):
👉 readFile() takes three arguments:
➣File name
➣Encoding (usually "utf8")
➣A callback function with err and data.
If the file exists, data gives the content. If not, it throws an error.
🔹 Step 3: Writing to a File
Let’s say we want to create or overwrite a file.
💡 Tip:
If the file doesn’t exist, Node creates it. If it does, Node replaces the entire content.
🔹 Step 4: Appending to a File
Want to add something without erasing what’s already there? Use appendFile():
This will add new text on a new line without deleting the previous content.
🔹 Step 5: Renaming a File
You can rename files easily:
🔹 Step 6: Deleting a File
To delete a file:
⚠️ Be careful — there’s no undo button here 😅
🧭 The path Module
The path module helps you build file paths safely.
Why do we need it?
Because file paths are different in Windows (\) and macOS/Linux (/).
So instead of hardcoding, Node provides tools to handle them properly.
🔹 Step 1: Import Path Module
🔹 Step 2: Join Paths Safely
Let’s say you want to access message.txt inside a folder named data.
Instead of writing "data/message.txt", do this:
👉 __dirname gives the current folder path automatically.
👉 path.join() adds the correct slashes for your system.
Analogy:
Think of path.join() as a GPS that finds the right route no matter which country (OS) you’re driving in 🚗
👋 Hey Awesome Campers!
I hope you’ve all been doing great and still coding strong 💪🔥!
So today, we’re going to learn something super practical — how to work with the file system and paths in Node.js using two important built-in modules:
👉 fs (File System)
👉 path (Path Utilities)
🗂️ What Are Modules Again?
Remember last time, we said modules in Node.js are like tools in a big developer toolbox — each tool (module) helps you do a specific job.
Now, two of the most powerful tools in that box are:
➡️fs → helps you interact with files and folders.
➡️path → helps you safely build file paths (because paths can get messy).
🧰 The fs Module – File System
The fs module lets Node.js work with your computer’s file system.
With it, you can:
➙Read files
➙Create new files
➙Write or append data
➙Rename or delete files
Think of it like Node’s hands 👐 that can open, read, and write notes in your computer’s drawers (folders).
🔹 Step 1: Import the fs module
Every time you want to use it, you must import it:
const fs = require('fs');
🔹 Step 2: Reading a File
Let’s say we have a text file named message.txt that says:
Hello Campers! Keep coding strong!
We can read it using two methods:
➣Synchronous – waits for the file to finish reading before moving on.
➣Asynchronous – doesn’t wait (recommended for most cases).
✅ Example (Asynchronous):
const fs = require('fs');
fs.readFile('message.txt', 'utf8', (err, data) => {
if (err) { console.error('Error reading file:', err);
return; }
console.log('File content:', data); });
👉 readFile() takes three arguments:
➣File name
➣Encoding (usually "utf8")
➣A callback function with err and data.
If the file exists, data gives the content. If not, it throws an error.
🔹 Step 3: Writing to a File
Let’s say we want to create or overwrite a file.
fs.writeFile('note.txt', 'You are doing amazing, Campers! 💪', (err) => {
if (err) throw err;
console.log('File created or updated successfully!'); });
💡 Tip:
If the file doesn’t exist, Node creates it. If it does, Node replaces the entire content.
🔹 Step 4: Appending to a File
Want to add something without erasing what’s already there? Use appendFile():
fs.appendFile('note.txt', '\nKeep going! The backend journey just started 🚀', (err) => {
if (err) throw err;
console.log('New line added!'); });
This will add new text on a new line without deleting the previous content.
🔹 Step 5: Renaming a File
You can rename files easily:
fs.rename('note.txt', 'motivation.txt', (err) => {
if (err) throw err;
console.log('File renamed successfully!'); });
🔹 Step 6: Deleting a File
To delete a file:
fs.unlink('motivation.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully!'); });
⚠️ Be careful — there’s no undo button here 😅
🧭 The path Module
The path module helps you build file paths safely.
Why do we need it?
Because file paths are different in Windows (\) and macOS/Linux (/).
So instead of hardcoding, Node provides tools to handle them properly.
🔹 Step 1: Import Path Module
const path = require('path');
🔹 Step 2: Join Paths Safely
Let’s say you want to access message.txt inside a folder named data.
Instead of writing "data/message.txt", do this:
const filePath = path.join(__dirname, 'data', 'message.txt');
console.log(filePath);
👉 __dirname gives the current folder path automatically.
👉 path.join() adds the correct slashes for your system.
Analogy:
Think of path.join() as a GPS that finds the right route no matter which country (OS) you’re driving in 🚗
🔹 Step 3: Get File Name, Extension, Directory
🔹 Step 4: Combine fs and path
They’re often used together — for example:
🧩 Common Mistakes
❌ Forgetting to include encoding like 'utf8' — gives you weird symbols instead of text.
❌ Using / or \ directly in file paths — may fail on other systems.
❌ Not handling errors — always check if (err) before using the data.
🪄 Debugging Tips
➤Use console.log(__dirname) to see where your script is running.
➤Use try/catch for synchronous methods or the err argument for async ones.
➤Always test after making changes — especially file paths!
Now go explore the fs and path modules a little more — experiment, break things, and fix them again 😄
const myPath = '/users/megersa/docs/note.txt'; console.log(path.basename(myPath)); // note.txt console.log(path.extname(myPath)); // .txt console.log(path.dirname(myPath)); // /users/megersa/docs 🔹 Step 4: Combine fs and path
They’re often used together — for example:
This ensures the file will be found even if the project runs on a different OS.const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'data', 'motivation.txt');
fs.readFile(filePath, 'utf8', (err, data) =>{
if (err) throw err;
console.log('Content:', data); });
🧩 Common Mistakes
❌ Forgetting to include encoding like 'utf8' — gives you weird symbols instead of text.
❌ Using / or \ directly in file paths — may fail on other systems.
❌ Not handling errors — always check if (err) before using the data.
🪄 Debugging Tips
➤Use console.log(__dirname) to see where your script is running.
➤Use try/catch for synchronous methods or the err argument for async ones.
➤Always test after making changes — especially file paths!
Now go explore the fs and path modules a little more — experiment, break things, and fix them again 😄
Assignment:
➤fs module
https://youtu.be/Z_p1yFGS0Ak?si=9iHYP2Wgjh0IqHpz
➤path module
https://youtu.be/p995SdRXw_E?si=ue0yfZ2Y0KVL3rDb
➤fs module
https://youtu.be/Z_p1yFGS0Ak?si=9iHYP2Wgjh0IqHpz
➤path module
https://youtu.be/p995SdRXw_E?si=ue0yfZ2Y0KVL3rDb
YouTube
Node.js Tutorial - 26 - fs Module
⚡️Syncfusion components: https://syncf.co/3Emhvnv
📘 Courses - https://learn.codevolution.dev/
💖 Support UPI - https://support.codevolution.dev/
💖 Support Paypal - https://www.paypal.me/Codevolution
💾 Github - https://github.com/gopinav
📱 Follow Codevolution…
📘 Courses - https://learn.codevolution.dev/
💖 Support UPI - https://support.codevolution.dev/
💖 Support Paypal - https://www.paypal.me/Codevolution
💾 Github - https://github.com/gopinav
📱 Follow Codevolution…
💻 Week 6 Day 4 Challenges — "Playing with Files & Paths"
🟢 Challenge 1: File Greeting Machine
Goal: Create a file named greeting.txt and write a nice message like
Then, read that file and print its content on the console.
Hints:
Use fs.writeFile() and fs.readFile()
Make sure to include the encoding 'utf8'
🟢 Challenge 2: Journal Writer ✍️
Goal: Create a program that keeps a running journal file.
Each time you run it, it should add a new line to a file named journal.txt with today’s date and a random motivational message.
Example Output in file:
Hints:
Use fs.appendFile()
Use new Date().toLocaleDateString() to get today’s date
🟡 Challenge 3: Path Explorer 🧭
Goal: Log the following info for the current file:
Its full path, folder name, file name, extension
Hints:
Use filename and dirname
Try these methods:
path.basename()
path.extname()
path.dirname()
Print everything in a pretty format.
🟡 Challenge 4: Safe File Reader 🚦
Goal: Write a small program that checks if a file exists before reading it.
If it exists → print “Reading file…” and display its content.
If it doesn’t → print “File not found, creating it now…” and create it with default text.
Hints:
Use fs.existsSync() to check file existence
Use fs.readFile() and fs.writeFile() accordingly
🟠 Challenge 5: Directory Manager 🗂️
Goal:
Create a folder named projects inside your working directory (if it doesn’t exist).
Then create 3 text files inside it:
day1.txt
day2.txt
day3.txt
After that, read all file names inside the folder and print them as a list.
Hints:
Use fs.mkdir() or fs.mkdirSync()
Use fs.readdir() to list files inside a directory
Use path.join(__dirname, 'projects', 'day1.txt') to safely create file paths
🟣 Challenge 6: Explore All Built-ins in fs & path 🔍
Goal: Explore and try as many built-in methods of fs and path as you can!
Create a file named exploration.js, and try using these (and more from docs):
🧱 Some Built-ins to Explore
In fs module:
➤fs.copyFile() – Copy a file
➤fs.stat() – Check file info (size, modified date, etc.)
➤fs.mkdir() – Create directory
➤fs.readdir() – Read folder contents
➤fs.unlink() – Delete file
➤fs.rename() – Rename file
➤fs.existsSync() – Check if file exists
➤fs.readFileSync() / fs.writeFileSync() – Synchronous versions
In path module:
➤path.join() – Safely join paths
➤path.resolve() – Get absolute path
➤path.parse() – Get path parts as an object
➤path.format() – Convert parsed object back to path
➤path.isAbsolute() – Check if path is absolute
Remember to always require('fs') and require('path') at the top of each file.
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
🟢 Challenge 1: File Greeting Machine
Goal: Create a file named greeting.txt and write a nice message like
“Hey Campers! You’re doing great 🌟”
Then, read that file and print its content on the console.
Hints:
Use fs.writeFile() and fs.readFile()
Make sure to include the encoding 'utf8'
🟢 Challenge 2: Journal Writer ✍️
Goal: Create a program that keeps a running journal file.
Each time you run it, it should add a new line to a file named journal.txt with today’s date and a random motivational message.
Example Output in file:
[2025-10-17] Keep going! Backend devs never quit 💪 [2025-10-18] You’re getting stronger with every challenge 🚀 Hints:
Use fs.appendFile()
Use new Date().toLocaleDateString() to get today’s date
🟡 Challenge 3: Path Explorer 🧭
Goal: Log the following info for the current file:
Its full path, folder name, file name, extension
Hints:
Use filename and dirname
Try these methods:
path.basename()
path.extname()
path.dirname()
Print everything in a pretty format.
🟡 Challenge 4: Safe File Reader 🚦
Goal: Write a small program that checks if a file exists before reading it.
If it exists → print “Reading file…” and display its content.
If it doesn’t → print “File not found, creating it now…” and create it with default text.
Hints:
Use fs.existsSync() to check file existence
Use fs.readFile() and fs.writeFile() accordingly
🟠 Challenge 5: Directory Manager 🗂️
Goal:
Create a folder named projects inside your working directory (if it doesn’t exist).
Then create 3 text files inside it:
day1.txt
day2.txt
day3.txt
After that, read all file names inside the folder and print them as a list.
Hints:
Use fs.mkdir() or fs.mkdirSync()
Use fs.readdir() to list files inside a directory
Use path.join(__dirname, 'projects', 'day1.txt') to safely create file paths
🟣 Challenge 6: Explore All Built-ins in fs & path 🔍
Goal: Explore and try as many built-in methods of fs and path as you can!
Create a file named exploration.js, and try using these (and more from docs):
🧱 Some Built-ins to Explore
In fs module:
➤fs.copyFile() – Copy a file
➤fs.stat() – Check file info (size, modified date, etc.)
➤fs.mkdir() – Create directory
➤fs.readdir() – Read folder contents
➤fs.unlink() – Delete file
➤fs.rename() – Rename file
➤fs.existsSync() – Check if file exists
➤fs.readFileSync() / fs.writeFileSync() – Synchronous versions
In path module:
➤path.join() – Safely join paths
➤path.resolve() – Get absolute path
➤path.parse() – Get path parts as an object
➤path.format() – Convert parsed object back to path
➤path.isAbsolute() – Check if path is absolute
Remember to always require('fs') and require('path') at the top of each file.
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
Week 6 Day 5 Node.js lesson
👋 Hello Amazing Campers!
How are you doing, brilliant minds?
I hope you’ve been coding strong, debugging smarter, and still taking time to enjoy your coffee ☕ / tea 🍵!
Today, we’re going to level up with two powerful built-in modules that make Node truly exciting and closer to real-world applications:
👉 The events module — for creating dynamic, reactive programs.
👉 The crypto module — for securing data and making your apps more trustworthy.
Let’s dive in 💪
🎉 1. The events Module — Making Node.js React!
🧠 What are “events”?
Think of “events” like real-life triggers — things that happen and we react to.
For example:
➤You click a button → it plays a sound.
➤You press a key → something appears on the screen.
➤A file finishes uploading → you get a success message.
In Node.js, we can do the same thing — not for buttons, but for system-level or custom actions.
💡 Analogy
Imagine you’re hosting a party 🎉.
You (the Event Emitter) shout, “Dinner is ready!” 🍝
➣Your guests (the Listeners) react — they grab a plate and start eating.
That’s how the events module works:
➙You emit an event (announce it).
➙Other parts of your code listen and react to that event.
⚙️ Step-by-step Example
🟢 Output:
💬 Explanation
EventEmitter is like a microphone 🎤.
➤on() means “Hey, listen for this kind of message.”
➤emit() means “Broadcast this message now!”
💡 Adding Parameters to Events
Events can also carry data — like a message or an object.
🟢 Output:
Here, the event greet sends data ('Megersa') — like passing a gift 🎁 to whoever listens.
⚙️ Real-World Example: File Upload or Payment Notification
You might emit events when:
➙A user logs in → emit "userLoggedIn".
➙A file finishes uploading → emit "uploadComplete".
➙A payment succeeds → emit "paymentSuccess".
This is how large-scale apps stay organized — events make different parts of your program talk to each other without being directly connected.
🔄 Once vs On
➣.on('event', fn) — listens every time the event happens.
➣.once('event', fn) — listens only for the first time.
Example:
🧩 Why Events Are Important
Node.js is event-driven — meaning everything (like requests, file reads, timers) happens through events behind the scenes.
When you use:
What really happens?
Node emits a “fileReadComplete” event internally when the file is done loading.
So when you use events, you’re learning how Node thinks and operates. 🧠
👋 Hello Amazing Campers!
How are you doing, brilliant minds?
I hope you’ve been coding strong, debugging smarter, and still taking time to enjoy your coffee ☕ / tea 🍵!
Today, we’re going to level up with two powerful built-in modules that make Node truly exciting and closer to real-world applications:
👉 The events module — for creating dynamic, reactive programs.
👉 The crypto module — for securing data and making your apps more trustworthy.
Let’s dive in 💪
🎉 1. The events Module — Making Node.js React!
🧠 What are “events”?
Think of “events” like real-life triggers — things that happen and we react to.
For example:
➤You click a button → it plays a sound.
➤You press a key → something appears on the screen.
➤A file finishes uploading → you get a success message.
In Node.js, we can do the same thing — not for buttons, but for system-level or custom actions.
💡 Analogy
Imagine you’re hosting a party 🎉.
You (the Event Emitter) shout, “Dinner is ready!” 🍝
➣Your guests (the Listeners) react — they grab a plate and start eating.
That’s how the events module works:
➙You emit an event (announce it).
➙Other parts of your code listen and react to that event.
⚙️ Step-by-step Example
// 1. Import the events module
const EventEmitter = require('events');
// 2. Create an instance of EventEmitter
const myEmitter = new EventEmitter();
// 3. Register (listen for) an event
myEmitter.on('party', () => { console.log('🎈 Someone started the party!'); });
// 4. Emit (trigger) the event myEmitter.emit('party'); 🟢 Output:
🎈 Someone started the party! 💬 Explanation
EventEmitter is like a microphone 🎤.
➤on() means “Hey, listen for this kind of message.”
➤emit() means “Broadcast this message now!”
💡 Adding Parameters to Events
Events can also carry data — like a message or an object.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('greet', (name) => {
console.log(👋 Hello, ${name}! Welcome to the camp.); });
myEmitter.emit('greet', 'Megersa');
🟢 Output:
👋 Hello, Megersa! Welcome to the camp. Here, the event greet sends data ('Megersa') — like passing a gift 🎁 to whoever listens.
⚙️ Real-World Example: File Upload or Payment Notification
You might emit events when:
➙A user logs in → emit "userLoggedIn".
➙A file finishes uploading → emit "uploadComplete".
➙A payment succeeds → emit "paymentSuccess".
This is how large-scale apps stay organized — events make different parts of your program talk to each other without being directly connected.
🔄 Once vs On
➣.on('event', fn) — listens every time the event happens.
➣.once('event', fn) — listens only for the first time.
Example:
myEmitter.once('start', () => console.log('Started!'));
myEmitter.emit('start'); // Works
myEmitter.emit('start'); // Ignored🧩 Why Events Are Important
Node.js is event-driven — meaning everything (like requests, file reads, timers) happens through events behind the scenes.
When you use:
fs.readFile('data.txt', callback); What really happens?
Node emits a “fileReadComplete” event internally when the file is done loading.
So when you use events, you’re learning how Node thinks and operates. 🧠
👍1
🔐 2. The crypto Module — Keeping Data Safe
Now that we know how to react to actions, let’s learn how to protect sensitive data like passwords, tokens, or API keys.
🧠 What is Cryptography?
Cryptography is the art of hiding information.
It’s like writing a diary in secret code — only someone with the right “key” can read it 🔑.
⚙️ Example 1: Creating a Simple Hash
🟢 Output:
💬 Explanation
➙sha256 is the algorithm (like a secret recipe).
➙update() is where we add the message we want to hide.
➙digest('hex') converts the encrypted result into readable text.
This means even if someone steals your data, they’ll only see gibberish 🧩.
⚙️ Example 2: Generating Random Tokens
You can also generate random secure values — perfect for unique user IDs, OTPs, or session keys.
🟢 Output:
Each time you run it — you’ll get a completely new random token 🎲.
⚙️ Example 3: Encrypt and Decrypt Messages (Optional, Advanced)
🟢 Output:
💬 In short:
events = “Let’s react to what happens!” 🎉
crypto = “Let’s keep our secrets safe!” 🔐
Together, they help you build apps that are dynamic, secure, and real-world ready.
So go ahead — explore the official documentation for both modules:
events
crypto
Because the best coders don’t memorize — they know where to look 👀.
Now that we know how to react to actions, let’s learn how to protect sensitive data like passwords, tokens, or API keys.
🧠 What is Cryptography?
Cryptography is the art of hiding information.
It’s like writing a diary in secret code — only someone with the right “key” can read it 🔑.
⚙️ Example 1: Creating a Simple Hash
const crypto = require('crypto');
// Create a hash object
const hash = crypto.createHash('sha256');
// Pass data into it
hash.update('password123');
// Convert it to hexadecimal format
const result = hash.digest('hex');
console.log('🔒 Hashed password:', result); 🟢 Output:
🔒 Hashed password: ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
💬 Explanation
➙sha256 is the algorithm (like a secret recipe).
➙update() is where we add the message we want to hide.
➙digest('hex') converts the encrypted result into readable text.
This means even if someone steals your data, they’ll only see gibberish 🧩.
⚙️ Example 2: Generating Random Tokens
You can also generate random secure values — perfect for unique user IDs, OTPs, or session keys.
const crypto = require('crypto');
const token = crypto.randomBytes(16).toString('hex');
console.log('🎟️ Your unique token:', token); 🟢 Output:
🎟️ Your unique token: 9b1de3a9e8a443e8b621be7634a32b4d Each time you run it — you’ll get a completely new random token 🎲.
⚙️ Example 3: Encrypt and Decrypt Messages (Optional, Advanced)
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Encrypt
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted; }
// Decrypt
function decrypt(encryptedText) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted; }
const message = 'Keep this secret';
const encrypted = encrypt(message);
const decrypted = decrypt(encrypted);
console.log('🔐 Encrypted:', encrypted);
console.log('🔓 Decrypted:', decrypted);
🟢 Output:
🔐 Encrypted: d4a7ff16e... 🔓 Decrypted: Keep this secret 💬 In short:
events = “Let’s react to what happens!” 🎉
crypto = “Let’s keep our secrets safe!” 🔐
Together, they help you build apps that are dynamic, secure, and real-world ready.
So go ahead — explore the official documentation for both modules:
events
crypto
Because the best coders don’t memorize — they know where to look 👀.
👍1
🧩 Week 6 Day 5 — Node.js Events & Crypto Challenges
🥇 Challenge 1: Event-Based Mini Chat Logger
You’re building a tiny “chat system” in Node.js using the events module.
Your goal:
➤Create an event emitter called chat.
➤Each time a user sends a message, emit a "message" event.
The listener should log the message with a timestamp — for example:
Hints:
➙Use new Date().toLocaleTimeString() for timestamps.
➙Use .on() to listen for messages.
Later, you can add events like "userJoined" or "userLeft" to make it more fun.
🥈 Challenge 2: Secure Password Hasher
Let’s make a small password hasher using the crypto module.
Your goal:
Ask the user for a password (store it as a parameter).
Hash it using SHA256.
Save the hash to a file called password.txt.
If you run the program again, it should check if the password matches the one in the file.
Hints:
Use ➤crypto.createHash('sha256').update(password).digest('hex').
➤Combine fs for file handling and crypto for hashing.
Common Pitfall:
Some might use createCipher by mistake — that’s for encryption, not hashing!
🥉 Challenge 3: Event-Driven Task Progress Tracker
You’re simulating how tasks run in the background — like downloading files or uploading data.
Your goal:
➤Create an event system for a fake “file download” process.
➤Emit events like "start", "progress", and "finish".
Log updates like:
Hints:
➤Use setInterval() to simulate progress.
➤Stop emitting "progress" when it reaches 100%.
Common Pitfall:
Forgetting to clear the interval — make sure to stop it after finishing.
🏆 Challenge 4: Crypto-Event Fusion (Advanced but Fun)
Now let’s combine what you learned — make a small user login simulator using both modules.
Your goal:
➤When the "login" event is emitted,
Generate a secure random token using crypto.randomBytes().
Log:
➤If the "logout" event is emitted,
Log: "User logged out. Session ended."
Hints:
Use .on() for both "login" and "logout".
Let the token be 16 bytes.
Common Pitfall:
Don’t generate the token before the event — generate it inside the listener.
🧭 Debugging Checklist
If something breaks, check:
➤Did you import the right module (events or crypto)?
➤Are your event names spelled exactly the same? ("login" vs "Login")
➤Did you forget to call .emit()?
➤Are you handling async actions correctly (like setInterval)?
💡 Pro Tips
➙Use console.table() or console.group() to make logs more readable.
➙Add a tiny delay between events to simulate real-world timing.
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
🥇 Challenge 1: Event-Based Mini Chat Logger
You’re building a tiny “chat system” in Node.js using the events module.
Your goal:
➤Create an event emitter called chat.
➤Each time a user sends a message, emit a "message" event.
The listener should log the message with a timestamp — for example:
[10:45:22 AM] Haregu: Hello everyone! Hints:
➙Use new Date().toLocaleTimeString() for timestamps.
➙Use .on() to listen for messages.
Later, you can add events like "userJoined" or "userLeft" to make it more fun.
🥈 Challenge 2: Secure Password Hasher
Let’s make a small password hasher using the crypto module.
Your goal:
Ask the user for a password (store it as a parameter).
Hash it using SHA256.
Save the hash to a file called password.txt.
If you run the program again, it should check if the password matches the one in the file.
Hints:
Use ➤crypto.createHash('sha256').update(password).digest('hex').
➤Combine fs for file handling and crypto for hashing.
Common Pitfall:
Some might use createCipher by mistake — that’s for encryption, not hashing!
🥉 Challenge 3: Event-Driven Task Progress Tracker
You’re simulating how tasks run in the background — like downloading files or uploading data.
Your goal:
➤Create an event system for a fake “file download” process.
➤Emit events like "start", "progress", and "finish".
Log updates like:
Download started...
Progress: 50%
Download complete! Hints:
➤Use setInterval() to simulate progress.
➤Stop emitting "progress" when it reaches 100%.
Common Pitfall:
Forgetting to clear the interval — make sure to stop it after finishing.
🏆 Challenge 4: Crypto-Event Fusion (Advanced but Fun)
Now let’s combine what you learned — make a small user login simulator using both modules.
Your goal:
➤When the "login" event is emitted,
Generate a secure random token using crypto.randomBytes().
Log:
User logged in.
Token: 9a1c0f42a3... ➤If the "logout" event is emitted,
Log: "User logged out. Session ended."
Hints:
Use .on() for both "login" and "logout".
Let the token be 16 bytes.
Common Pitfall:
Don’t generate the token before the event — generate it inside the listener.
🧭 Debugging Checklist
If something breaks, check:
➤Did you import the right module (events or crypto)?
➤Are your event names spelled exactly the same? ("login" vs "Login")
➤Did you forget to call .emit()?
➤Are you handling async actions correctly (like setInterval)?
💡 Pro Tips
➙Use console.table() or console.group() to make logs more readable.
➙Add a tiny delay between events to simulate real-world timing.
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
👍1
Week 6 Day 6 Node.js lesson
👋 Hello Campers!
Hope you’ve been doing great and coding strong. now... it’s time to build something magical — your very first server! 💻
Today we’re diving into one of the most powerful and important modules in Node.js — the HTTP module.
This is what allows Node.js to “talk” to the internet — to send and receive data between your computer and other systems.
🌐 What Is the HTTP Module?
In short:
Think of it like running your own little restaurant 🍴
➣The client (like your browser or Postman) is the customer — it comes with a request (“I want a pizza!”).
➣The server (your Node.js app) is the chef — it listens for that request, prepares something (HTML, JSON, text, etc.), and sends a response back (“Here’s your pizza 🍕”).
This back-and-forth is the request-response cycle — the heart of web communication.
🧠 Why Do We Need It?
Normally, websites live on remote servers (like those run by Google, GitHub, or Netflix).
But when you build your own backend, you’re creating your own mini version of that — a Node.js app that can:
➤Respond to requests (like GET /home or POST /login)
➤Send data (like HTML pages or JSON responses)
➤Communicate with databases and APIs
And the tool that makes all this possible inside Node is — the http module.
⚙️ Setting It Up
You don’t need to install it — it’s a built-in module! 🎉
Just import it like this:
🍽️ Creating Your First Server
Let’s make a tiny server that listens to requests and sends back a simple message.
🧩 Step-by-Step Explanation
Let’s break this down:
➤Importing the Module
You’re bringing in the built-in HTTP module that knows how to handle web traffic.
➤Creating the Server
Here you’re building a kitchen (the server) where the chef (Node) will prepare responses.
The (req, res) part is
➙ your request (what the customer asks for) and
➙ your response (what you serve back).
➤Handling Requests
➙res.writeHead(200) means “everything’s OK” — that’s the HTTP status code 200.
➙"Content-Type": "text/plain" tells the browser what kind of data is coming (plain text, HTML, JSON, etc.).
➙res.end() finishes the response and sends it back to the client.
➤Starting the Server
➙The .listen() method starts your server and tells it to listen for requests on port 3000 (like a door number).
When you visit http://localhost:3000 in your browser — boom 💥 — your server responds!
🌉 Understanding Request and Response
Every time a browser makes a request, Node gives you two objects:
➤req (Request): holds information about what the user asked for (like URL, headers, method).
Example:
➤res (Response): controls what you send back (HTML, JSON, or text).
You can even send back HTML instead of plain text:
👋 Hello Campers!
Hope you’ve been doing great and coding strong. now... it’s time to build something magical — your very first server! 💻
Today we’re diving into one of the most powerful and important modules in Node.js — the HTTP module.
This is what allows Node.js to “talk” to the internet — to send and receive data between your computer and other systems.
🌐 What Is the HTTP Module?
In short:
The http module allows your computer (running Node.js) to act as a web server — to receive requests and send responses.
Think of it like running your own little restaurant 🍴
➣The client (like your browser or Postman) is the customer — it comes with a request (“I want a pizza!”).
➣The server (your Node.js app) is the chef — it listens for that request, prepares something (HTML, JSON, text, etc.), and sends a response back (“Here’s your pizza 🍕”).
This back-and-forth is the request-response cycle — the heart of web communication.
🧠 Why Do We Need It?
Normally, websites live on remote servers (like those run by Google, GitHub, or Netflix).
But when you build your own backend, you’re creating your own mini version of that — a Node.js app that can:
➤Respond to requests (like GET /home or POST /login)
➤Send data (like HTML pages or JSON responses)
➤Communicate with databases and APIs
And the tool that makes all this possible inside Node is — the http module.
⚙️ Setting It Up
You don’t need to install it — it’s a built-in module! 🎉
Just import it like this:
const http = require("http");
🍽️ Creating Your First Server
Let’s make a tiny server that listens to requests and sends back a simple message.
const http = require("http");
// Create a server
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Campers! Your server is running successfully 🚀"); });
// Start the server
server.listen(3000, () => {
console.log("Server is running on http://localhost:3000"); }); 🧩 Step-by-Step Explanation
Let’s break this down:
➤Importing the Module
const http = require("http"); You’re bringing in the built-in HTTP module that knows how to handle web traffic.
➤Creating the Server
const server = http.createServer((req, res) => { ... }); Here you’re building a kitchen (the server) where the chef (Node) will prepare responses.
The (req, res) part is
➙ your request (what the customer asks for) and
➙ your response (what you serve back).
➤Handling Requests
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Campers!"); ➙res.writeHead(200) means “everything’s OK” — that’s the HTTP status code 200.
➙"Content-Type": "text/plain" tells the browser what kind of data is coming (plain text, HTML, JSON, etc.).
➙res.end() finishes the response and sends it back to the client.
➤Starting the Server
server.listen(3000, () => { console.log("Server is running on http://localhost:3000"); }); ➙The .listen() method starts your server and tells it to listen for requests on port 3000 (like a door number).
When you visit http://localhost:3000 in your browser — boom 💥 — your server responds!
🌉 Understanding Request and Response
Every time a browser makes a request, Node gives you two objects:
➤req (Request): holds information about what the user asked for (like URL, headers, method).
Example:
console.log(req.url); // Might show "/about"
console.log(req.method); // Might show "GET" ➤res (Response): controls what you send back (HTML, JSON, or text).
You can even send back HTML instead of plain text:
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Hello Campers!</h1>
<p>This is your first Node.js server 😎</p>");
🚪 Ports and Localhost Explained
➣Think of localhost as your “computer’s name” on your local network.
➣And port as a specific door where your server listens for visitors.
Different apps can use different ports:
➙Port 3000 → Your Node app
➙Port 5000 → Another service (like a database)
➙Port 80 → The default web traffic port (used by browsers)
When you type http://localhost:3000, it’s like saying:
🔍 Handling Multiple Routes
You can serve different responses based on the URL path that’s requested:
Now your little web server can handle multiple routes — just like how a restaurant serves different dishes depending on what you order. 🍜
🧭 Debugging Checklist
If something doesn’t work:
➤Did you run node filename.js in your terminal?
➤Did you use the right port number in your browser?
➤Did you close your previous server (you can stop it using Ctrl + C)?
➤Check for typos in res.writeHead or res.end().
💡 Pro Tips
➣Always call res.end() — if you forget it, the response never finishes.
➣Use different content types:
➙text/html → for HTML pages
➙application/json → for API data
➙text/plain → for simple text
➣Use req.method (GET, POST, etc.) when you start building APIs later.
🌻 Wrap-Up
You now understand:
➤What the http module does
➤How to create and start your own web server
➤How the request–response cycle works
➤How to serve multiple routes
This is the foundation of backend development — every server, API, or website you’ll ever build rests on this concept.
➣Think of localhost as your “computer’s name” on your local network.
➣And port as a specific door where your server listens for visitors.
Different apps can use different ports:
➙Port 3000 → Your Node app
➙Port 5000 → Another service (like a database)
➙Port 80 → The default web traffic port (used by browsers)
When you type http://localhost:3000, it’s like saying:
“Go to my own computer, and knock on door 3000.”
🔍 Handling Multiple Routes
You can serve different responses based on the URL path that’s requested:
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Welcome to the homepage!"); }
else if (req.url === "/about") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About us: We’re learning Node.js together 🌱"); }
else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 - Page not found"); } });
server.listen(3000, () => console.log("Server is running on http://localhost:3000")); Now your little web server can handle multiple routes — just like how a restaurant serves different dishes depending on what you order. 🍜
🧭 Debugging Checklist
If something doesn’t work:
➤Did you run node filename.js in your terminal?
➤Did you use the right port number in your browser?
➤Did you close your previous server (you can stop it using Ctrl + C)?
➤Check for typos in res.writeHead or res.end().
💡 Pro Tips
➣Always call res.end() — if you forget it, the response never finishes.
➣Use different content types:
➙text/html → for HTML pages
➙application/json → for API data
➙text/plain → for simple text
➣Use req.method (GET, POST, etc.) when you start building APIs later.
🌻 Wrap-Up
You now understand:
➤What the http module does
➤How to create and start your own web server
➤How the request–response cycle works
➤How to serve multiple routes
This is the foundation of backend development — every server, API, or website you’ll ever build rests on this concept.
💪 Node.js HTTP Module Challenges
⚡ Challenge 1: Multi-Page Text Server
Goal: Create a Node.js server that serves different text messages depending on the URL route.
Requirements:
➣Use the built-in http module only (no frameworks).
➣Handle these routes:
➙"/ "→ Respond with “Welcome to My Server!”
➙"/about" → Respond with “This server was built by [Your Name]!”
➙"/contact" → Respond with “Email us at example@mail.com.”
➙Any other route → Respond with “404: Page Not Found”
➣Set proper headers (Content-Type: text/plain).
💡 Hints:
➙Use req.url to check the route.
➙Use res.writeHead() and res.end() to send responses.
➙Don’t forget to call res.end() in every route.
🌐 Challenge 2: HTML Response Server
Goal: Serve HTML content from your Node server instead of just plain text.
Requirements:
➣Create a simple homepage using res.writeHead(200, { "Content-Type": "text/html" }).
➣Send a proper HTML structure — at least a <h1>, <p>, and a <footer>.
➣Add a second route (/info) that sends another HTML response (for example, “Server created by Campers!”).
➣Add CSS inline (for fun!) — maybe color your <h1> green or blue.
💡 Hints:
You can use backticks (``) for multi-line HTML:
res.end
💾 Challenge 3: JSON API Server (Mini Data Endpoint)
Goal: Create a mini API that sends JSON data (not HTML or text).
Requirements:
➣Use Content-Type: application/json.
➣Handle the route /api/users.
When the user visits /api/users, respond with an array of fake user objects:
➣For any other route, send a 404 JSON response:
💡 Hints:
➙Use JSON.stringify() to convert JS objects into JSON strings before sending them.
➙Use conditionals (if (req.url === "/api/users")) to check which route is being visited.
⚠️ Common Pitfalls:
➤Forgetting JSON.stringify() → leads to [object Object] in the browser.
➤Sending two responses for one request (only one res.end() allowed per request).
🧠 Debugging Checklist
Before calling for help, check these:
➤Did you start your server with node yourFile.js?
➤Is your terminal showing “Server is running…”?
➤Did you go to the correct port (e.g., http://localhost:3000)?
➤Did you stop your previous server using Ctrl + C before running again?
➤Is your res.end() present in all responses?
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
⚡ Challenge 1: Multi-Page Text Server
Goal: Create a Node.js server that serves different text messages depending on the URL route.
Requirements:
➣Use the built-in http module only (no frameworks).
➣Handle these routes:
➙"/ "→ Respond with “Welcome to My Server!”
➙"/about" → Respond with “This server was built by [Your Name]!”
➙"/contact" → Respond with “Email us at example@mail.com.”
➙Any other route → Respond with “404: Page Not Found”
➣Set proper headers (Content-Type: text/plain).
💡 Hints:
➙Use req.url to check the route.
➙Use res.writeHead() and res.end() to send responses.
➙Don’t forget to call res.end() in every route.
🌐 Challenge 2: HTML Response Server
Goal: Serve HTML content from your Node server instead of just plain text.
Requirements:
➣Create a simple homepage using res.writeHead(200, { "Content-Type": "text/html" }).
➣Send a proper HTML structure — at least a <h1>, <p>, and a <footer>.
➣Add a second route (/info) that sends another HTML response (for example, “Server created by Campers!”).
➣Add CSS inline (for fun!) — maybe color your <h1> green or blue.
💡 Hints:
You can use backticks (``) for multi-line HTML:
res.end
( <html>
<body style="font-family:sans-serif;text-align:center">
<h1 style="color:green;">Welcome Campers!</h1>
<p>This is your first HTML page from a Node.js server!</p>
</body> </html> ); 💾 Challenge 3: JSON API Server (Mini Data Endpoint)
Goal: Create a mini API that sends JSON data (not HTML or text).
Requirements:
➣Use Content-Type: application/json.
➣Handle the route /api/users.
When the user visits /api/users, respond with an array of fake user objects:
[ { "id": 1, "name": "Alice", "age": 22 }, { "id": 2, "name": "Bob", "age": 25 }, { "id": 3, "name": "Charlie", "age": 30 } ] ➣For any other route, send a 404 JSON response:
{ "error": "Not Found" } 💡 Hints:
➙Use JSON.stringify() to convert JS objects into JSON strings before sending them.
➙Use conditionals (if (req.url === "/api/users")) to check which route is being visited.
⚠️ Common Pitfalls:
➤Forgetting JSON.stringify() → leads to [object Object] in the browser.
➤Sending two responses for one request (only one res.end() allowed per request).
🧠 Debugging Checklist
Before calling for help, check these:
➤Did you start your server with node yourFile.js?
➤Is your terminal showing “Server is running…”?
➤Did you go to the correct port (e.g., http://localhost:3000)?
➤Did you stop your previous server using Ctrl + C before running again?
➤Is your res.end() present in all responses?
💥 share your solutions in the group,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
🔥1