Create a basic website with HTML and CSS using Node.js. We’ll load different HTML pages and a CSS file using the fs
(File System) module and http
core module.
Create a server file
website.js
const http = require("http");
http
.createServer((req, resp) => {
resp.write("page check");
resp.end();
})
.listen(3200);
This creates a simple HTTP server.
Load HTML file using fs
const http = require("http");
const fs = require("fs");
http
.createServer((req, resp) => {
fs.readFile("html/home.html", "utf-8", (error, data) => {
if (error) {
resp.writeHead(500, { "content-type": "text/plain" });
resp.end("Internal Server Error");
return false;
}
resp.write(data);
resp.end();
});
})
.listen(3200);
This loads the home.html
file and displays its content on the browser using asynchronous fs.readFile()
.
Sync vs Async in fs
(Used in Header)
In the code below, we use:
let collectHeaderData = fs.readFileSync("html/header.html", 'utf-8');
Synchronous (Sync)
fs.readFileSync()
blocks further execution until the file is fully read.
Use it for small files like header.html
where immediate availability is needed.
Later in the same code:
fs.readFile("html"+file+".html", 'utf-8', (error, data) => {
...
});
Asynchronous (Async)
fs.readFile()
does not block the code. It continues and runs the callback when data is ready.
Better for performance, especially for larger or external files.
Handle HTML and CSS File Together
const http = require('http');
const fs = require('fs');
http.createServer((req, resp) => {
// Sync: Header file loaded before anything else
let collectHeaderData = fs.readFileSync("html/header.html", 'utf-8');
let file = "/home";
if (req.url !== '/') {
file = req.url;
}
// Async: Load HTML file with callback
if (req.url !== '/style.css') {
fs.readFile("html" + file + ".html", 'utf-8', (error, data) => {
if (error) {
resp.writeHead(500, { "content-type": "text/plain" });
resp.end("internal server error");
return false;
}
resp.write(collectHeaderData + "" + data);
resp.end();
});
}
// Serve CSS with correct content-type
else if (req.url === '/style.css') {
fs.readFile("html/style.css", 'utf-8', (error, data) => {
if (error) {
resp.writeHead(500, { "content-type": "text/plain" });
resp.end("css not found");
return false;
}
resp.writeHead(200, { "content-type": "text/css" });
resp.end(data);
});
}
}).listen(3200);
Why CSS Didn’t Load Earlier?
Because we didn’t set "Content-Type": "text/css"
.
Browsers need the correct header to apply styles.