Objective: Gain practical experience with the Node.js File System module, building servers, and using Express for routing.
- File System Task: Learn to read and write files.
- Building a Server: Create a server that renders HTML.
- Express Routing: Implement routing with Express.
- PUT Request Implementation: Handle PUT requests to update JSON data.
Goal: Manipulate text files and HTML with Node.js.
- In the
node-server
folder, createtextfile.txt
. - Add sample text to
textfile.txt
. - Run
node src/index.js
to output file contents in the console. - Create
index.html
with basic HTML structure. - Modify
src/index.js
to serveindex.html
, and rerun the server.
Goal: Build a server to render HTML content.
-
Enhance
index.html
with more complex HTML. -
Use the following code in
src/index.js
to serveindex.html
:var http = require("http"), fs = require("fs"); var server = http .createServer(function (request, response) { fs.readFile("./index.html", function (err, html) { if (err) { throw err; } response.writeHeader(200, { "Content-Type": "text/html" }); response.write(html); response.end(); }); }) .listen(8080);
-
Start the server and navigate to
http://localhost:8080/
to see the HTML page. -
Modify the server for different URL conditions, returning a 404 status for unmatched routes.
Goal: Implement Express routing to handle JSON data.
-
Install Express dependencies: Run
npm install
in the terminal. -
Open
server.js
and set up Express:var express = require("express"); var app = express(); app.use(express.json()); // For parsing JSON requests
-
Add a GET route in
server.js
to returnprofiles.json
content athttp://localhost:8080/profiles
. -
Test the server with
node src/server.js
and visit the URL in a browser or Postman. -
Implement an additional GET route for
http://localhost:8080/profiles/view
to return profile information as HTML.
Visiting http://localhost:8080/profiles/view
displays profile names and bios as HTML.
Goal: Update profiles.json
via PUT requests.
-
Open
server.js
in thelogger
folder. -
Implement a PUT route
/api/profiles/:id
. -
Update
profiles.json
with new data upon receiving a PUT request. -
Test using Postman with the following JSON data:
{ "firstname": "Jessica", "lastname": "Jones", "age": 35 }
- Ensure correct functionality by replacing the specified profile in
profiles.json
. - Handle non-existent IDs with a
404 Not Found
status.
- Success:
PUT http://localhost:3000/profiles/1
updates the profile and returns200 OK
. - Failure:
PUT http://localhost:3000/profiles/567
returns404 Not Found
if the ID does not exist.
This README provides a step-by-step guide to understand file handling, server setup, Express routing, and PUT request handling in Node.js.