Lab1
zip6 files5 kBIn Node.js lab 1
README.md
Lab 01-04: Simple Note-Taking API
📋 Objective
Create a simple HTTP server that can save and retrieve notes using Node.js core modules (http, fs, path) with async/await and events.
🎯 Learning Goals
- Use
httpmodule to create a server - Use
fsmodule to read/write files - Use
pathmodule for file paths - Use
async/awaitfor asynchronous operations - Use
EventEmitterto log events
📝 Requirements
Your server should handle these routes:
- GET
/notes- Read all notes fromnotes.jsonand return them as JSON - POST
/notes- Add a new note tonotes.json - GET
/- Return a simple welcome message
🚀 Getting Started
-
Create a file called
server.jsin this folder -
Use the template provided in
server-template.js -
Fill in the TODO sections
-
Test your server using:
node server.js -
Test with browser or PowerShell:
# Get all notes Invoke-RestMethod -Uri http://localhost:3000/notes # Add a note (Method 1: Using single quotes) Invoke-RestMethod -Uri http://localhost:3000/notes -Method Post -ContentType "application/json" -Body '{"text":"My first note"}' # Add a note (Method 2: Using double quotes - escape inner quotes with backtick) Invoke-RestMethod -Uri http://localhost:3000/notes -Method Post -ContentType "application/json" -Body "{`"text`":`"My first note`"}" # Add a note (Method 3: Using a variable - recommended for complex JSON) $body = @{text="My first note"} | ConvertTo-Json Invoke-RestMethod -Uri http://localhost:3000/notes -Method Post -ContentType "application/json" -Body $body
✅ Checklist
- Server starts on port 3000
- GET
/returns welcome message - GET
/notesreads fromnotes.jsonand returns JSON - POST
/notesadds a note tonotes.json - Uses
async/awaitfor file operations - Uses
EventEmitterto log when notes are added - Handles errors with try/catch
- Uses
pathmodule for file paths
📚 Hints
- Use
fs.promises.readFile()andfs.promises.writeFile()for async file operations - Parse JSON with
JSON.parse()and stringify withJSON.stringify() - Use
path.join(__dirname, 'notes.json')for the file path - Check
req.methodandreq.urlto handle different routes - Use
EventEmitterto emit 'noteAdded' event when a note is created
🎓 What You'll Practice
- ✅ Node.js core modules (http, fs, path)
- ✅ Async/await with Promises
- ✅ EventEmitter for logging
- ✅ JSON parsing and stringifying
- ✅ HTTP request handling
Good luck! 🚀