Ejs & Express & Node.js

Sheryians Coding School

Backend with Node & express & ejs


Folder Structure

prerequisites

  • npm i express
  • npm i ejs

  • server.js
  • 
    // server.js
    
    
    const express = require('express')
    const app = express();
    const path = require('path')
    const fs = require('fs');
    app.set("view engine", "ejs")
    app.use(express.json())
    app.use(express.urlencoded({ extended: true }));
    app.use(express.static(path.join(__dirname, "public")))
    
    app.get("/", function (req, res) {
      fs.readdir(`./files`, function (err, files) {
      res.render("index", { files: files });
      })
    })
    
    // app.get("/file/:filename", function (req, res) {
    //   fs.readFile(`/files/${req.params.filename}`, "utf-8", function (err, filedata) {
    
    //   res.render('show', { filename: req.params.filename, filedata: filedata });
    
    //   })
    // })
    
    app.get("/file/:filename", function (req, res) {
      const filePath = path.join(__dirname, 'files', req.params.filename); // Construct the file path
      fs.readFile(filePath, "utf-8", function (err, filedata) {
        // Render the "show" view and pass the filename and filedata to it
        res.render('show', { filename: req.params.filename, filedata: filedata });
      });
    });
    
    app.get('/edit/:filename', function (req, res) {
      res.render("edit",{filename: req.params.filename});
    })
    
    app.post('/edit', function (req, res) {
     fs.rename(`./files/${req.body.previous}`,`./files/${req.body.new}`,function(err){
      res.redirect("/")
     })
    })
    
    app.post("/create", function (req, res) {
    
      fs.writeFile(`./files/${req.body.title.split(' ').join('')}.txt`, req.body.details, function (err) {
        res.redirect("/")
    
      })
    })
    
    app.listen(3000, () => {
      console.log("server is running on port 3000");
    })
    
    

  • index.ejs
  •     
            
    //index.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Blog Site</title>
      <script src="https://cdn.tailwindcss.com"></script>
    </head>
    
    <body  style="background-color: black; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
      <div class="main w-full min-h-screen bg-zinc-900">
        <div class="form p-10 text-white">
    
          <form action="/create" method="post">
            <input class="block w-full rounded-md outline-none mt-2 px-5 py-2 resize-none bg-zinc-800" type="text"
              placeholder="Title goes here" name="title">
            <textarea class="block w-full rounded-md outline-none mt-2 px-5 py-2 resize-none bg-zinc-800"
              placeholder="Write your task details here..." name="details"></textarea>
            <input class="mt-2 bg-blue-600 px-5 py-2 rounded" type="submit" value="create">
          </form>
    
        </div>
    
        <div class="tasks flex gap-3 flex-wrap p-10">
    
          <% if(files.length> 0){%>
    
            <% files.forEach(function(val){ %>
    
              <div class="task min-w-72 px-3 py-4 rounded-md bg-zinc-800
            ">
                <h1 style="color: white; font-size:medium ;" class="text-white text-3xl tracking-tighter">
                  <%=val%>
                </h1>
                <div class="flex w-full justify-between items-center mt-3">
                  <a class="text-blue-500 inline-block " href="/file/<%= val %>">Read More.</a>
                  <a href="/edit/<%=val %>">edit filename</a>
                </div>
              </div>
    
              <% }) %>
    
                <%}else{ %>
                  <h3 class="text-white">No tasks yet</h3>
                  <% } %>
    
        </div>
    </body>
    
    </html>
        
    

  • show.ejs
  •     
    
    //show.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>show.ejs</title>
    <script src="https://cdn.tailwindcss.com"></script>
    </head>
    
    <body style="background-color: black; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
      <div style="background-color: black; padding: 10px;">
    
        <a style="color: blue; margin-bottom:10; display: inline-block; " href="/">Go Back to home</a>
        <h1 style="font-size: 40px; color:white;">
          <%= filename %>
        </h1>
    
        <p style="color: white; margin-top:5px ;"> <%= filedata %> </p>
      </div>
    </body>
    
    </html>
        
    

  • edit.ejs
  •     
            
    //edit.ejs
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>edit</title>
    <script src="https://cdn.tailwindcss.com"></script>
    </head>
    
    <body style="background-color: black;">
      <div style="background-color: black; padding: 10px;">
    
        <a style="color: blue; margin-bottom:10; display: inline-block; " href="/">Go Back to home</a>
    
        <form action="/edit" method="post">
          <input class="block w-full text-gray-700 rounded-md outline-none mt-2 px-5 py-2 resize-none bg-zinc-800" type="text"
            placeholder="Previous name" name="previous" value="<%= filename%>">
    
          <input class="block w-full rounded-md outline-none mt-2 px-5 py-2 resize-none bg-zinc-800" type="text"
            placeholder="New Name" name="new">
    
          <input class="mt-2 bg-yellow-600 px-5 py-2 rounded" type="submit" value="Update Name">
        </form>
    
      </div>
    </body>
    </html>
        
    
    M A N I

    Iam M A N I ,i am an aspiring BCA student formed an obsession with Blogging, SEO,and Helping Beginners.

    Post a Comment

    Previous Post Next Post