Full Stack Camp
Open in Telegram
Fullstack Camp | Learn. Build. Launch. Join us for a hands-on journey through HTML, CSS, JavaScript, React, Node.js, Express & MongoDB ā all in one place. Use this bot to search for lessons. @FullstackCamp_assistant_bot DM: @Tarikey6
Show moreThe country is not specifiedThe category is not specified
235
Subscribers
-124 hours
No data7 days
+330 days
Posts Archive
š§© Week 7 Day 2 Challenges ā Routing in Express
š§ Challenge 1: Simple Blog Router
Goal: Create a small blog route system using Express.
Requirements:
Create routes for:
ā¤GET /posts ā return a list of blog post titles (hardcoded in an array)
ā¤GET /posts/:id ā return a single blog post based on the ID parameter
ā¤POST /posts ā return āNew post added!ā when a new post is sent
Use app.route() to chain the GET and POST routes for /posts.
Hint: You can store blog posts like this:
const posts = [ { id: 1, title: "My First Blog" }, { id: 2, title: "Learning Express Routing" }, ];
šŖ Remember: Use req.params.id to get the dynamic part of the URL.
š¬ Challenge 2: Query String Search
Goal: Add a route that uses query parameters to filter users.
Requirements:
ā¤Create a GET /users route.
Pass query strings like ?name=John or ?age=25.
ā¤Return a message like:
āāSearching for user named Johnā
āāSearching for user aged 25ā
āāSearching for user named John aged 25ā
Hint: Use req.query.name and req.query.age to extract the values.
Check if they exist using simple if-statements.
š Challenge 3: Organized Routes with Router Module
Goal: Organize your routes into a separate file using express.Router().
Requirements:
ā¤Create a new folder /routes and a file products.js.
ā¤Inside products.js, create routes for:
āGET /products ā āAll products listā
āGET /products/:id ā āProduct ID is ___ā
āImport and use this router in your main app.js.
Hint: Use:
ā¤const router = express.Router();
and export it with:
module.exports = router;
Then in app.js:
ā¤const productsRouter = require('./routes/products'); app.use('/products', productsRouter);
š§ Debugging Tips
ā£If routes donāt respond ā check app.listen() port.
ā£If a route never runs ā check if you included app.use() after your router import.
ā£If req.params or req.query is undefined ā print them with console.log(req.params, req.query) to debug.
šÆ After Youāre Done
š„share your solutions in the group,
š„invite a friend,
and as always ā
š„stay well, stay curious, and stay coding āļøš§ 6ļøā£ Organizing Routes in Separate Files (Router Module)
When your app grows, you donāt want all your routes in one file ā that would be a spaghetti nightmare š.
Express provides a built-in feature called the Router module to separate routes logically.
Example:
š Project structure:
project/ ā
āāā app.js
āāā routes/
āāā users.js
š routes/users.js
š app.jsconst express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('All Users'); }); router.get('/:id', (req, res) => { res.send(User ID: ${req.params.id}); }); module.exports = router;
const express = require('express');
const app = express();
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(3000, () => { console.log('Server running on port 3000'); });
Now:
ā¤/users ā āAll Usersā
ā¤/users/2 ā āUser ID: 2ā
š§ Analogy: Think of Router like folders for your code ā each folder (route file) keeps related āpagesā or āfeaturesā tidy and easy to manage.
š” Tips
ā¤Always use meaningful route names (not random strings).
ā¤Keep route logic short ā if it grows, move logic into a controller file later.
ā¤Use documentation: https://expressjs.com/en/guide/routing.htmlWeek 7 Day 2 - Routing in Express.js
š Hey Campers!
I hope youāve all been doing awesome and coding your hearts out! ā¤ļø
Itās time to meet Express routing, the magic that makes your server organized, scalable, and super clean! š
Today weāll be diving into routing in Express.js ā how your app listens to different URLs and decides what to do for each one.
š 1ļøā£ What Is a Route? (Simple Analogy)
Think of your Express app as a restaurant š½ļø.
āEach route is like a different waiter that handles specific customer orders:
āWhen someone says, āI want pizza š,ā one waiter handles pizza orders.
āWhen someone says, āI want pasta š,ā another waiter handles pasta orders.
āSimilarly, when your users visit:
ā£/home ā you might send your homepage.
ā£/about ā you might send info about your app.
ā£/api/users ā you might return some JSON data.
Each route in Express defines what happens when someone requests a specific URL and method (GET, POST, PUT, DELETE, etc.).
āļø 2ļøā£ Defining Routes (The Basics)
In Express, routes are created using methods like
⣠app.get(),
ā£app.post(),
ā£app.put(), and
⣠app.delete() ā these correspond to HTTP methods.
Hereās the basic format:
app.METHOD(PATH, HANDLER)
ā¤METHOD ā The HTTP request type (e.g., GET, POST).
ā¤PATH ā The route path (e.g., "/", "/about", "/users").
ā¤HANDLER ā A function that runs when someone visits that path.
š§ Example:
const express = require('express');
const app = express();
// Home route
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!'); });
// About route
app.get('/about', (req, res) => {
res.send('About Us Page'); });
// Contact route
app.get('/contact', (req, res) => {
res.send('Contact Us Here!'); });
// Start the server app.listen(3000, () => { console.log('Server running on port 3000'); });
š§© Try It Out!
Go to:
ā¤http://localhost:3000/ ā āWelcome to the Home Page!ā
ā¤http://localhost:3000/about ā āAbout Us Pageā
ā¤http://localhost:3000/contact ā āContact Us Here!ā
š§ŗ 3ļøā£ Route Parameters (req.params)
Sometimes you need to pass dynamic values in your routes.
For example: /users/1 or /users/5 ā You donāt want to write 100 routes for each user, right?
Thatās where route parameters come in.
Example:
 š§ Analogy: Think of it like a template ā :id is a placeholder that Express replaces with whatever comes in the URL. šTest it: ā£Visit /users/10 ā shows āUser ID is 10ā ā¤Visit /users/200 ā shows āUser ID is 200ā š 4ļøā£ Query Strings (req.query) Query strings are used for filtering or searching information. They come after a ? in the URL ā like this: /search?keyword=javascript&sort=asc Example:app.get('/users/:id', (req, res) => { const userId = req.params.id; // extract the value res.send(User ID is ${userId}); });
š Visit: http://localhost:3000/search?keyword=express&sort=asc ā Output: āSearching for express, sorted by ascā š§ Analogy: Itās like ordering coffee ā with options: /coffee?milk=yes&sugar=no Express reads your preferences and gives the right cup. š§© 5ļøā£ Route Chaining (app.route()) When you have multiple methods (GET, POST, PUT, DELETE) for the same path ā instead of writing app.get() and app.post() separately, you can chain them using app.route(). Example:app.get('/search', (req, res) => { const { keyword, sort } = req.query; res.send(Searching for ${keyword}, sorted by ${sort}); });
app.route('/books')
.get((req, res) => res.send('Get all books'))
.post((req, res) => res.send('Add a new book'))
.put((req, res) => res.send('Update a book'));
š§ Analogy: Imagine a āBooks Counterā in a library š:
Same counter (same route /books)
But different actions: āGet,ā āAdd,ā or āUpdate.ā
This keeps your code cleaner and more organized.š Why Express is Everywhere
Express is the foundation for many popular frameworks:
āNext.js (for React)
āNestJS
āSails.js
Itās used by companies like Uber, Accenture, and IBM ā because itās simple, flexible, and super fast. š
š Further Learning & Docs
you can explore for further detail or when you want to refer something:
š§¾ Official Express Documentation
š MDN Express Guide
š¬ Recap
By now, you should understand:
ā
What Express.js is
ā
Why itās useful
ā
How it simplifies Node.js
ā
How to set it up and start a basic server
Next time, weāll start actually building routes, using middleware, and handling requests.
So rest your brain a little, hydrate š§, and get ready ā the fun part begins tomorrow! š
Untill next time:
š„invite a friend,
and as always ā
š„stay well, stay curious, and stay coding āļø
š Week 7 Day 1 ā Welcome to Express.js! š
Hey amazing campers! š
I hope youāve been doing fantastic and still coding hard! šŖ
Youāve come so far ā from writing your first console.log() to building backend systems using pure Node.js. Now, youāre stepping into the next big world of backend development ā Express.js ā and trust me, youāre going to love it! š
š§ Why Express.js?
Letās imagine youāre building a restaurant š½ļø.
ā£In Node.js, you built everything yourself ā tables, chairs, the oven, even the door handle. You handled every guest manually (remember http.createServer()? š
).
ā£In Express.js, you still own the restaurant, but now you have a team of helpers. They automatically open the door, take orders, serve food, and clean up ā you just tell them what to do and when to do it.
Thatās what Express does ā it simplifies the hard work of handling servers, routes, and responses so that you can focus on building logic, not managing the plumbing.
āļø What is Express.js?
Express.js is a web framework for Node.js that helps you:
āBuild web applications and APIs faster.
āHandle routes (different URLs/endpoints) easily.
āManage requests and responses in a clean way.
āAdd middlewares (helpers that process data in between) ā for example, logging, authentication, or parsing JSON.
In short:
Node.js gives you raw power. Express gives you structure and simplicity.Example: Node.js
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome Home!'); }
else if (req.url === '/about' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Us'); }
else {
res.writeHead(404);
res.end('Not Found'); } });
server.listen(3000, () => console.log('Server running...'));
Express.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome Home!'); });
app.get('/about', (req, res) => {
res.send('About Us'); });
app.listen(3000, () => console.log('Server running...'));
See how much cleaner and simpler it gets?
Thatās the beauty of Express. š”
š§± Setting Up Express
Before using Express, make sure you:
āHave Node.js installed
check using: node -v
āInitialize your project npm init -y
āInstall Express
npm install express
Once done, you can create a file like server.js and write:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello Express!'));
app.listen(3000, () => console.log('Server running on port 3000'));
āRun it with:
node server.js
āNow visit http://localhost:3000 ā boom š„ ā youāve just built your first Express server!
š§© Key Concepts to Understand Early
1. App Object
When you call express(), it gives you an app object that represents your entire application.
Youāll use it to define routes, use middleware, and listen for requests.
2. Routing
Routes are simply paths where your app responds.
āapp.get('/home', handler) ā handles GET requests to /home
āapp.post('/login', handler) ā handles POST requests to /login
3. Middleware
Think of middleware as checkpoints š§± in your app.
Before reaching the final route, your data can pass through multiple middlewares for:
ā¤Logging requests
ā¤Validating input
ā¤Checking authentication
ā¤Parsing JSON data
Weāll dive deep into middleware in upcoming lessons.š Project 6: Book Management System with Node.js (No Express Yet)
š Hey Campers!
I hope you've been doing great and still coding strong!
Youāve learned so much about Node.js this week ā now it's time to use your skills and build something real before entering the world of Express.
So welcome to your next project:
ā
šÆ Goal of the Project
Build a Book Management System using Node.js without Express, where users can:
ā Add a new book
ā View all books
ā Search books
ā Delete books
ā (Optional) Expose basic HTTP API using http module
ā Data must be saved in a .json file using the fs module
š ļø 1. Project Setup
book-manager/
ā
āāā data/
ā āāā books.json // will store all books
āāā app.js // main file
āāā .env // for PORT or FILE_PATH
āāā package.json
āāā helpers/ // optional folder for organizing code
š¦ 2. Initialize the Project
Inside your project folder:
āinstall the dependancies you need
āCreate a .env file
āLoad .env in app.js:
ārequire('dotenv').config();
šļø 3. Create & Use books.json
Inside /data/books.json, start with:
[]
This is where books will be saved.
āļø 4. Features to Build (One by One)
ā
(1) Add a Book
Each book should have:
ā£id ā generated using uuid
ā£title
ā£author
ā£publishedYear
ā£addedAt ā using dayjs()
š Steps / Hints:
ā¤Use readline-sync to ask user for book details
ā¤Read current books from books.json using fs.readFileSync
ā¤Push new book object into the list
Save back to books.json using fs.writeFileSync
š” Checkpoint: If you run it twice, books should be saved permanently!
ā
(2) List All Books
ā¤Read from books.json
ā¤Display in a clean format using ā¤console.table() or simple forEach
ā
(3) Search a Book by Title/Author
ā¤Ask user to enter a search word
ā¤Use .filter() to find matching books
ā
(4) Delete a Book
ā£Ask for a book id
ā£Filter out the book and save updated list back
ā” 5. Add HTTP Server Later
After finishing CLI version, you can upgrade your project so that it gets all the books as a json.
ā Common Mistakes & How to Fix Them
ā¤JSON.parse error
Happens when books.json is empty or has invalid JSON.
ā
Make sure the file starts with [] or contains valid JSON.
ā¤File not found
Caused by an incorrect path in .env.
ā
Use a correct relative path like ./data/books.json.
ā¤Data not saved
Happens when you forget to use fs.writeFileSync() or fs.writeFile().
ā
Always save the data after modifications.
ā¤App crashes on the first run
Occurs when books.json doesnāt exist yet.
ā
Check and create it using:
if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, '[]');
ā¤App freezes / doesnāt exit
Usually caused by not closing readline properly.
ā
Call process.exit() or rl.close() after completing actions.
When youāre done building your project:
š„ 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 9 ā Node.js Utility Packages Challenges
š§© Challenge 1: āThe Smart Greeterā ā readline + moment
š§ Goal
Create a small CLI app that:
ā£Asks the user for their name and birth year using the readline (or readline-sync) module.
ā£Calculates their age using moment or dayjs.
ā£Prints a friendly greeting message that includes the current date and their age.
š Hints
āUse moment().year() or dayjs().year() to get the current year.
āSubtract birth year to find age.
āUse .format('dddd, MMMM Do YYYY') to make the date pretty.
š Challenge 2: āSecret Configuratorā ā dotenv + nodemon
š§ Goal
Create a .env file that contains: ā£
APP_NAME=CampManager ā£PORT=8080
ā¤In your Node app, use dotenv to load these variables.
ā¤When the app runs, log: Running CampManager on port 8080
ā¤Use nodemon to keep the server auto-refreshing while you make changes.
š Hints
āImport dotenv and call ārequire('dotenv').config().
āAccess variables via process.env.APP_NAME and process.env.PORT.
āStart your server using nodemon index.js instead of node index.js.
šŖ Challenge 3: āCrypto Wallet ID Generatorā ā uuid
š§ Goal
Youāre building a fake crypto wallet app šŖ
ā£Each time a new wallet is created, generate a unique ID for it using uuid.
ā£Make an array of users.
ā¤Each user has a name and an id generated by uuidv4().
ā¤Print the wallet info to the console.
š Bonus
Add a timestamp using moment() or dayjs() when each wallet is created (e.g., "Created at: 2025-10-31 10:15:22").
š
Challenge 4: āMini Task Loggerā ā readline + uuid + dayjs + fs
š§ Goal
Build a simple CLI task tracker:
ā¤Use readline-sync to ask:
āTask name
āDue date (YYYY-MM-DD)
ā¤Generate a unique task ID using uuid.
ā¤Save the task in a tasks.txt file with: ID | Task | Due Date | Created At
ā¤Use dayjs() or moment() to add the creation timestamp.
ā¤After adding, print: Task added successfully! ā
š Bonus Ideas
ā¤Read and display all saved tasks on startup.
ā¤Highlight overdue tasks in red (you can use console colors like \x1b[31m for red).
š ļø Debugging Checklist
ā
Did you install all needed packages (dotenv, uuid, moment or dayjs, readline-sync, nodemon)?
ā
Are you running your file with nodemon instead of node?
ā
Did you remember to call .config() for dotenv?
ā
Are you formatting your dates using .format()?
ā
Are your UUIDs showing unique values each time?
When you are done:
š„share your solutions in the group,
š„invite a friend,
and as always ā
š„stay well, stay curious, and stay coding āļøā° 4. moment.js or dayjs ā āThe Time Tamerā
š Analogy
Dates and times in JavaScript are like spaghetti š ā hard to handle and easily tangled.
If you ever worked with new Date(), you know how confusing it can get.
Thatās why developers use moment.js or dayjs ā simple libraries for formatting and manipulating dates.
āļø Installation
You can pick one:
š§© Example (using moment)npm install momentornpm install dayjs
const moment = require("moment");
console.log("Current Time:", moment().format("YYYY-MM-DD HH:mm:ss"));
console.log("Tomorrow:", moment().add(1, 'days').format("dddd, MMMM Do"));
š§ Output:
Current Time: 2025-10-31 15:42:00
Tomorrow: Saturday, November 1st
š§© Example (using dayjs)
const dayjs = require("dayjs");
console.log(dayjs().format("YYYY-MM-DD"));
console.log(dayjs().add(7, 'day').format("dddd, MMM D"));
š Both are great ā dayjs is lighter and faster, while moment has more features.
š More Info
š Moment Docs
š Day.js Docs
š¬ 5. readline / readline-sync ā āTalking to Your Terminalā
š Analogy
So far, your apps ātalkā by logging things ā but what if your app could ask you something and wait for your answer?
Thatās what the readline module does ā it lets your Node app take input from the user directly from the terminal.
š§© Example (built-in readline)
šÆ Output:const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question("What is your name? ", (answer) => { console.log(Hello, ${answer}! Welcome to Node Camp!); rl.close(); });
What is your name? Haregu
Hello, Haregu! Welcome to Node Camp!
š§© Easier Version (using readline-sync)
npm install readline-sync
š More Info š readline Docs š readline-sync Docsconst readlineSync = require("readline-sync"); const name = readlineSync.question("What is your name? "); console.log(Nice to meet you, ${name}!);
š Week 6 Day 9 ā Power Tools of Node.js (nodemon, dotenv, uuid, moment/dayjs, readline)
š Hey amazing campers!
I hope youāve been doing great and coding hard.
Today, weāll take a relaxed but powerful final step in our Node.js fundamentals journey.
Weāll explore some super useful tools and packages that make backend development smoother, faster, and more professional.
These tools are like the āgadgets in a superheroās belt.ā
You could code without them ā but why struggle when you can have cool powers? š
So letās go one by one.
š 1. Nodemon ā āThe Auto-Refresherā
š Analogy
Imagine youāre writing an essay, and after every small edit, you must close the Word document and reopen it to see changes.
Thatās annoying, right?
Thatās what happens with Node ā every time you edit your code, you need to stop and restart the server manually.
Nodemon fixes that!
āļø What It Does
nodemon automatically restarts your Node.js server every time you change your file.
So you can focus on coding, not on typing node app.js again and again.
šŖ Installation
You only install it once globally:
npm install -g nodemonThen, instead of running:
node server.jsyou run:
nodemon server.jsNow, every time you save your file, it restarts the server automatically! ā” š§ Example
const http = require("http"); const server = http.createServer((req, res) => { res.end("Hello, campers!"); }); server.listen(3000, () => console.log("Server running on port 3000"));If you change the message to āWelcome to Node Camp!ā and hit save ā Nodemon automatically restarts and updates it live šÆ š More Info š Nodemon Docs šæ 2. dotenv ā āThe Secret Keeperā š Analogy Imagine youāre building a magic potion ā you wouldnāt shout your secret recipe to the world, right? In coding, API keys, database passwords, and tokens are your secret ingredients. They must stay hidden from the public. Thatās where dotenv comes in! āļø What It Does dotenv helps you store sensitive data (like passwords or keys) in a hidden file called .env. You can use them safely inside your project without exposing them to everyone. šŖ Installation
npm install dotenvš§© Example 1ļøā£ Create a file called .env PORT=4000 API_KEY=12345-SECRET 2ļøā£ In your app.js file:
require("dotenv").config(); console.log(process.env.PORT); console.log(process.env.API_KEY);3ļøā£ Output: 4000 12345-SECRET ā Your secrets stay safe and out of your code! š More Info š dotenv Docs š 3. uuid ā āThe ID Generatorā š Analogy Every human has a unique fingerprint, right? Every object in your app ā a user, post, or task ā also needs a unique ID to be identified. Instead of making them manually (id: 1, id: 2ā¦), uuid generates them automatically and ensures theyāre globally unique! āļø Installation
npm install uuidš§© Example
const { v4: uuidv4 } = require("uuid"); const user1 = { id: uuidv4(), name: "Alice" }; const user2 = { id: uuidv4(), name: "Bob" }; console.log(user1); console.log(user2);š§ Output:
{ id: '8f14e45f-ea4f-4a9a-a2f3-f2383b1a1f9c', name: 'Alice' } { id: 'a9b31e4a-8f74-4b43-85b7-6a9f1b7b123a', name: 'Bob' }šÆ Every time you run the code, youāll get different IDs! š More Info š uuid Docs
Repost from Edemy
When I graduated, I was so focused on building stability, earning my own income, becoming independent, and finding financial freedom. I felt a constant pressure to figure everything out quickly, as if success had a deadline.
Without knowing, that pressure made me push myself harder. I worked on multiple things at once, trying to fast-forward the process because I thought success had to come quickly. But over time, I learned that everything is a matter of time. Hard work, patience, and consistency eventually pay off but never overnight.
Looking back, the habits I once questioned my obsession with improving, my impatience to grow, my constant drive to solve every problem were actually what shaped me the most. They kept me moving forward when things felt slow or uncertain.
There were times I doubted whether hard work truly pays off. But it does just not always on our timeline.
I still have a long way to go, many goals to reach, and lessons to learn. But now I know for sure with discipline, focus, and persistence, anything is possible.
If thereās one thing Iād share as advice:
Donāt rush your journey. Growth takes time and so does success. Be patient with yourself, stay consistent, and keep learning.
Opportunities appear when youāre prepared for them, thatās when luck actually works.
Because luck isnāt random; it happens when preparation meets opportunity.
Have a productive week!
@edemy251
Week 6 Day 8 Challenges
ā” Challenge 1: Create and Share Your Own npm Project
Goal: Build and publish (locally, not to npm) your own mini npm project.
š§ Instructions:
āCreate a new folder (e.g., my-utils).
āRun npm init -y to create a package.json.
āInside, create a file called index.js that exports a simple function ā e.g., greet(name) or add(a, b).
āUse module.exports to make your function usable in another project.
āCreate another folder (e.g., test-app), install your local module using:
npm install ../my-utils
āImport it using require() and test your function!
š” Hint:
Youāre basically creating your own mini library ā just like āLodashā or āChalkā!
ā” Challenge 2: Use 3 npm Packages in a Mini App
Goal: Use multiple npm packages in one Node.js app.
š§ Instructions:
āCreate a new project (npm init -y).
āInstall these packages: npm install chalk figlet axios
āCreate a small script (app.js) that:
ā£Uses figlet to print a fancy title.
ā£Uses chalk to colorize messages.
ā£Uses axios to fetch a random quote from a free API (like https://api.quotable.io/random).
āPrint the quote beautifully in the console.
š” Hint:
Each of these libraries adds flavor ā figlet for style, chalk for colors, and axios for real data!
ā” Challenge 3: Version Control & Dependency Practice
Goal: Understand how versioning and dependencies work.
š§ Instructions:
āOpen your package.json.
āInstall an older version of a package (for example): npm install chalk@4.1.2
āCheck how it changes in package.json.
āNow update it using: npm update chalk
āObserve the difference in version numbers and understand what ^ and ~ symbols mean.
āFinally, delete your node_modules folder and reinstall dependencies with: npm install
š” Hint:
Youāre learning how developers manage updates and keep their projects stable over time.
š„share your solutions in the group,
š„Celebrate your progress
š„invite a friend,
and as always ā
š„stay well, stay curious, and stay coding āļøš§ Analogy: npm as a Personal Toolbox š§°
Imagine your Node project is a workshop.
ā¤package.json = the inventory list of all your tools.
ā¤node_modules/ = your tool cabinet, full of ready-to-use tools.
ā¤npm install = bringing new tools from the ātool storeā (npm registry).
ā¤npm uninstall = throwing away a tool you donāt need anymore.
Simple and practical, right?
āļø Common npm Commands
CommandWhat it does
npm initāāāCreate a new package.json file interactively
npm init -yāāāāCreate a package.json file quickly with default settings
npm install <package>āāāInstalls a package locally
npm install -g <package>āāāā Installs a package globally (for all projects)
npm uninstall <package> āāāāRemoves a package
npm list āāāāShows all installed packages
npm outdated āāāShows which packages need updates
npm update āāāUpdates packages to latest versions
ā ļø Common Pitfalls
ā Deleting node_modules accidentally ā no worries! Just run npm install again.
ā ļø Forgetting to run npm init ā your project wonāt track dependencies.
ā ļø Installing globally (-g) unnecessarily ā only do it for tools like nodemon or typescript.
ā Manually editing node_modules ā never do that! npm manages it for you.
š§© Debugging Checklist
ā
Can you run npm -v and node -v successfully?
ā
Did you initialize the project with npm init -y?
ā
Does package.json list your installed packages?
ā
Does your code successfully import and use the package?
ā
If you get āmodule not found,ā check if youāre in the correct project folder!
š¬ Quick Tip
You can explore packages on š https://www.npmjs.com
Search anything ā āweather,ā āquotes,ā āAI,ā or āgamesā ā and youāll find tons of libraries ready to use!
š» Wrap-Up
And thatās it, Campers š ā youāve officially entered the npm ecosystem, where developers share and build upon each otherās tools.
Now, go ahead and play around ā install random fun packages, try them out, and explore your new coding toolbox.
Week 6 Day 8 Nodejs lesson
š Hey Campers!
I hope youāre all doing fantastic š, coding strong š», and feeling proud of how far youāve come!
Now, weāre entering the modern Node developerās toolbox:
š npm (Node Package Manager) and the magical file that runs every Node project ā package.json.
šÆ What Youāll Learn Today
By the end of this lesson, youāll understand:
What npm is and why we use it
What packages and modules are
What package.json does and how to create it
How to install and use third-party libraries
How to manage dependencies in a Node.js project
š§ What Is npm (Node Package Manager)?
Letās start simple.
When we built apps before, we used Nodeās built-in modules like fs, path, and http.
But what if you want to:
ā£Send an email from your app? š©
ā£Connect to a database like MongoDB? šļø
ā£Build a web server faster than writing everything from scratch? ā”
You donāt have to reinvent the wheel each time.
Developers all around the world share reusable code called packages (or libraries) ā and npm helps you install and manage them.
Think of npm as the āPlay Storeā or āApp Storeā for Node.js packages.
You just search, install, and use ā just like downloading apps on your phone.
š¦ What Is a Package?
A package is simply a collection of code someone else wrote to solve a common problem.
For example:
ā£express ā helps create web servers easily
ā£axios ā helps make HTTP requests
ā£chalk ā adds color to your console messages
ā£dotenv ā manages environment variables safely
Each package lives in a huge online database called npm registry (https://www.npmjs.com).
šļø What Is package.json?
When you start a Node project, thereās one important file that keeps everything organized:
š package.json
Itās like your projectās resume ā it tells others (and Node) what your app is, what version itās on, and what dependencies it needs to work.
Example of a simple package.json file:
{ "name": "my-first-node-app",
"version": "1.0.0",
"description": "A simple Node project to learn npm",
"main": "index.js",
"scripts": { "start": "node index.js" },
"author": "Your Name",
"license": "ISC",
"dependencies": {} }
šŖ Step-by-Step: Setting Up npm in Your Project
Letās create your first npm project together š
ā¤Create a folder for your project
Example:
mkdir npm-demo
cd npm-demo
ā¤Initialize npm
This command creates a package.json file automatically.
npm init -y
The -y flag means āyes to all defaultsā (it fills the name, version, etc., automatically).
ā¤Check the generated file
Open the new package.json ā youāll see info like project name, version, etc.
ā¤Install your first package! š
Letās install a fun one: chalk (it helps color your console messages).
npm install chalk
This will:
āAdd a new folder called node_modules (where all packages are stored)
āAdd a new section in package.json ā "dependencies": { "chalk": "^5.0.0" }
šØ Using the Installed Package
Now, letās use it in your code.
Create a file called index.js:
// Import chalk
import chalk from "chalk"; // for Node v18+ (ES Modules syntax)
// Print some colorful messages console.log(chalk.green("Hello Campers!"));
console.log(chalk.blue.bold("Welcome to npm world!"));
console.log(chalk.red("Errors donāt scare us anymore š"));
If your Node version doesnāt support import, you can use:
const chalk = require("chalk");
Now run:
node index.js
š Youāll see colorful text printed in your terminal. š
šŖ How npm Works Behind the Scenes
When you run npm install <package>, npm:
ā¤Downloads the package (and all the smaller packages it depends on)
ā¤Saves it inside a hidden folder node_modules/
ā¤Updates your package.json and creates a package-lock.json (to lock exact versions)
This means when someone else downloads your project, they donāt need the packages yet ā they just run:
npm install
and npm will automatically install everything listed in package.json for them. šŖšŖ Week 6 Day 7 Challenges ā HTTP Module Deep Dive
ā” Challenge 1: The Greeting Server
Goal: Build a server that greets users by their name using query parameters.
Requirements:
When users visit /greet?name=Alice, respond with:
š āHello Alice! Welcome to our Node.js server!ā
When thereās no name provided, respond with:
š āHello Guest! Please tell me your name next time!ā
Hints:
Use the url module to parse query strings.
Remember: url.parse(req.url, true) gives you an object with .query.
Common Pitfalls:
Forgetting to set content type headers (res.writeHead).
Forgetting to end() your response.
ā” Challenge 2: The Feedback Collector
Goal: Build a server that accepts POST requests with feedback messages and displays them on GET requests.
Requirements:
When users send a POST request with text data (like āGreat course!ā), save it temporarily in an array.
When users visit /feedback using a GET request, show all feedback messages as a simple list.
Hints:
Youāll need to collect data from req.on('data') and req.on('end').
Use a global array variable to store feedbacks (like let feedbacks = []).
You can test POST requests using Postman, Thunder Client, or curl.
Example curl:
curl -X POST -d "Great session today!"
http://localhost:3000/feedback
Common Pitfalls:
ā£Not converting chunks to string (chunk.toString()).
ā£Forgetting that POST requests send data asynchronously ā your response should come after req.on('end').
ā” Challenge 3: Mini User Info Server
Goal: Create a mini user info service that uses route parameters and query parameters together.
Requirements:
ā£URL format: /users/123?name=Alice&country=Ethiopia
ā£The server should respond with:
š āUser ID: 123 ā Name: Alice ā Country: Ethiopiaā
ā£If any part is missing, respond with a friendly error message like
š āOops! Please include user ID, name, and country.ā
Hints:
ā£Split the URL by / to extract req.params. (e.g., const parts = req.url.split('/'))
ā£Then use url.parse(req.url, true) to extract query parameters.
ā£Remember to check both parts before constructing your message.
Common Pitfalls:
ā£Mixing up pathname and full req.url.
ā£Forgetting to handle when the user doesnāt pass enough parameters.
ā£Returning responses before parsing is complete.
š± Bonus Exploration Idea
If you finish early, try connecting these challenges:
Store the feedback from Challenge 2 per user ID like in Challenge 3.
Or, make Challenge 1 greet users differently depending on time of day.
š„share your solutions in the group,
š„Celebrate your progress
š„invite a friend,
and as always ā
š„stay well, stay curious, and stay coding āļøš” To test this, use a tool like Postman or curl by downloading the extensions, or even your browserās DevTools.
Example:
POST http://localhost:3000
Body: name=Alice&age=20
The server will print:
Data received: name=Alice&age=20
š§ So Whatās Happening?
ā£req.on("data") ā listens for incoming chunks of data.
ā£req.on("end") ā triggers after all data is received.
ā£The body data often arrives in small chunks ā Node listens and collects them.
š£ļø 3. req.params (Route Parameters)
In plain Node.js (without Express), you handle route parameters manually ā but itās great to understand before we move to frameworks.
Route parameters are like placeholders in your route.
For example:
"/users/123 "
Here, 123 might be a userās ID.
You can capture it by splitting the path:
Go to:const http = require("http"); const server = http.createServer((req, res) => { const parts = req.url.split("/"); console.log(parts); // Example: /users/123 if (parts[1] === "users" && parts[2]) { const userId = parts[2]; res.writeHead(200, { "Content-Type": "text/plain" }); res.end(User ID requested: ${userId}); } else { res.writeHead(404); res.end("Not Found"); } }); server.listen(3000, () => console.log("Server running on port 3000"));
http://localhost:3000/users/42
Output:
User ID requested: 42
šÆ Analogy: If your server were a library, /books/12 means
āHey librarian, bring me the book with ID 12!āš§ Before You Move On ā£Keep experimenting with different request types (GET, POST). ā£Try printing req.method, req.url, and req.headers for deeper understanding. ā£Refer to Node.js documentation: š https://nodejs.org/api/http.html
Week 6 Day 7 ā Deep Dive into HTTP Module + URL + Request Data
Hey there, brilliant campers! š
I hope youāve been doing amazingly well and coding even better!
Youāve built your first servers, sent responses, and even served HTML and JSON. Thatās already a huge step into backend development. š
But guess what?
Our servers so far could only listen and respond.
Today, weāll make them understand what users are saying!
Letās dive deeper into how we handle URLs, query parameters, and request data (req.body & req.params) using Nodeās http and url modules.
š§ Big Picture First
When someone sends a request to your server, itās like a customer placing an order at a cafĆ©.
ā£The server = the barista ā
ā£The request (req) = the order (āOne latte, please!ā)
ā£The response (res) = the finished drink returned to the customer.
But sometimes, customers want customized orders:
āOne latte, with extra sugar, and my name on it please!āThatās what URL parameters, query strings, and request bodies are for ā letting the client send specific data along with the request. Letās unpack these step-by-step š š§© 1. The url Module ā Understanding the Request URL When a user visits:
http://localhost:3000/about?name=Alice&age=20
This URL has two parts:
ā£Path: /about ā like the āpageā they want
ā£Query: ?name=Alice&age=20 ā extra info sent to the server
To handle this, Node gives us the url module.
š§® Example: Parsing a URL
const http = require("http");
const url = require("url");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true); // true = parse query as object
console.log(parsedUrl);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Check your console for parsed URL details!"); });
server.listen(3000, () => console.log("Server running on port 3000"));
Now, go to:
http://localhost:3000/about?name=Alice&age=20
Youāll see something like this in the console:
{ pathname: '/about', query: { name: 'Alice', age: '20' } }
So now your server knows:
ā£The page (pathname) is /about.
ā£The userās data (query) is { name: 'Alice', age: '20' }.
šÆ Using the Query Parameters in Responses
Now try visiting: "/ "ā āHello Guestā "/?name=Alice" ā āHello Aliceā š Query parameters are like extra details added to the order slip. š¦ 2. Getting Data from req.body (POST Requests) So far, weāve only used GET requests, where data comes through the URL. But what if the user submits a form or sends JSON data to the server? Thatās where the request body comes in. āļø Analogy: Think of req.body as a sealed envelope the user sends. The server must open and read it before knowing whatās inside. š¬ Example: Reading Request Body (POST Request)const http = require("http"); const url = require("url"); http.createServer((req, res) => { const parsed = url.parse(req.url, true); const name = parsed.query.name || "Guest"; res.writeHead(200, { "Content-Type": "text/plain" }); res.end(Hello ${name}, welcome to our server!); }) server.listen(3000, () => console.log("Server running on port 3000"));
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST") {
let body = "";
req.on("data", chunk => { body += chunk.toString(); // converting buffer to string });
req.on("end", () => { console.log("Data received:", body);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Data received successfully!"); }); }
else {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Send a POST request to this server!"); } });
server.listen(3000, () => console.log("Server running on port 3000"));šŖ 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
(
<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 āļøšŖ 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:
ā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.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:
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>");
