DEV Community

ShadyAlefrangy
ShadyAlefrangy

Posted on

How To Use EJS to Template Your Node Application with nodejs pure

Hi,
today I will explain how to use node.js pure to make this following:

_1. Create new Web Server.

  1. Create 3 separate HTML pages with different content.
  2. Create two more pages header.html and footer.html as pages layout.
  3. Create a request handler that returns the content of one of these pages based on URL pathname.
  4. 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}`);
});
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

// 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>
Enter fullscreen mode Exit fullscreen mode

// 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

// create the footer page

<footer>
    <p>Author: Shady Alefrangy</p>
    <p><a href="example@example.com">example@example.com</a></p>
</footer>

Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

});

Thanks

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Really enjoy using EJS even though frontend JavaScript framework like React, Vue, Angular and Svelte exist now. It's still good for building a simple website or doing some testing.