How To Use EJS to Template Your Node Application with nodejs pure
ShadyAlefrangy
Posted on May 24, 2022
Hi,
today I will explain how to use node.js pure to make this following:
_1. Create new Web Server.
- Create 3 separate HTML pages with different content.
- Create two more pages header.html and footer.html as pages layout.
- Create a request handler that returns the content of one of these pages based on URL pathname.
- Each page return consists of header.html page then page content then footer.html._
1. Create new Web Server
// create the main file with .mjs extension like this (main.mjs)
// Import ES Modules
import http from 'http';
import fs from "fs/promises";
import path from 'path';
import { fileURLToPath, URL } from 'url';
// __dirname not included is ES Modules
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Paths for layout files
const headerPath = path.join(__dirname, 'header.html');
const footerPath = path.join(__dirname, 'footer.html');
// Set port as constant
const port = 5000;
// Now create web server
const server = http.createServer(async (req, res) => {});
// Run the server
server.listen(port, () => {
console.clear();
console.log(`Server is running... at http://localhost:${port}`);
});
2. Create 3 separate HTML pages with different content
// create the first page (index.html)
<!DOCTYPE html>
<html lang="en">
{#header#}
<body>
<h1>This is index Page</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quod odit quis debitis quos suscipit enim? Officiis, eum! Tempora voluptates libero perspiciatis laudantium iusto animi suscipit? Quam illo nihil minima ut, in facere aspernatur, repellendus sit, laudantium cupiditate suscipit? Facilis veniam aspernatur iusto sunt necessitatibus aliquid accusamus voluptatum eos! Atque, unde!
</p>
{#footer#}
</body>
</html>
// create the second page
<!DOCTYPE html>
<html lang="en">
{#header#}
<body>
<h1>This is about Page</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quod odit quis debitis quos suscipit enim? Officiis, eum! Tempora voluptates libero perspiciatis laudantium iusto animi suscipit? Quam illo nihil minima ut, in facere aspernatur, repellendus sit, laudantium cupiditate suscipit? Facilis veniam aspernatur iusto sunt necessitatibus aliquid accusamus voluptatum eos! Atque, unde!
</p>
{#footer#}
</body>
</html>
// Create the third page
<!DOCTYPE html>
<html lang="en">
{#header#}
<body>
<h1>This is users Page</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quod odit quis debitis quos suscipit enim? Officiis, eum! Tempora voluptates libero perspiciatis laudantium iusto animi suscipit? Quam illo nihil minima ut, in facere aspernatur, repellendus sit, laudantium cupiditate suscipit? Facilis veniam aspernatur iusto sunt necessitatibus aliquid accusamus voluptatum eos! Atque, unde!
</p>
{#footer#}
</body>
</html>
3. Create two more pages header.html and footer.html as pages layout
// create the header page.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node JS Server</title>
</head>
// create the footer page
<footer>
<p>Author: Shady Alefrangy</p>
<p><a href="example@example.com">example@example.com</a></p>
</footer>
4. Create a request handler that returns the content of one of these pages based on URL pathname.
5. Each page return consists of header.html page then page content then footer.html
I code this with asynchronous approach with (async/await)
const server = http.createServer(async (req, res) => {
const url = new URL(http:${req.headers.host}${req.url}
);
const fileName = url.pathname;
const renderedFilePath = path.join(__dirname, 'public', `${fileName}`);
try {
await fs.access(renderedFilePath)
let header = await fs.readFile(headerPath, {encoding: 'utf-8'});
let footer = await fs.readFile(footerPath, {encoding: 'utf-8'});
let content = await fs.readFile(renderedFilePath, {encoding: 'utf-8'});
content = content.replace('{#header#}', header);
content = content.replace('{#footer#}', footer);
res.end(content);
} catch {
res.statusCode = 404;
res.end('File not found');
}
});
Thanks
💖 💪 🙅 🚩
ShadyAlefrangy
Posted on May 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Simplifying Excel Table Parsing in Node.js with @libs-jd/xlsx-parse-table
November 9, 2024
javascript Introducing sast-scan: A Lightweight SAST npm Package for JavaScript Security
October 19, 2024