Band Generator using JS (Node JS)

Band Generator using JS (Node JS)

Introduction

  • Lets make a random Bandname generator cus why not..

  • It'll take a random adjective and random noun form a long list and put them together to give weird bandname.

  • It'll do all this WHEN you press a button.

Dependencies

  • First we install the packages/dependecies:

    • Express

    • body-parser

    • nodemon (optional)

  • We will use the Express framework for all our backend functions.

  • we use the body-parser middleware to take user input to the server.

  • Nodemon is just a nice package to have, it makes it so that you dont have to manually restart your server while you work on it.

EJS

  • For this project I wont be creating any HTML files instead I'll be creating EJS files which are basically a mix of javascript and HTML that is converted to HTML when you render it.

  • Its basically used to get a more dynamic HTML.

Partials

  • When using EJS to create dynamic HTML generally the only thing changing is the body of the html.

  • So we can split the head and footer (Which will generally be the same on all pages) into separate files called partials these will be later included into the other body EJS files.

  • in the header EJS file we will be having the head tag with the link to the CSS stylesheet.

  • When linking to a file to EJS file you cant do it the same way you do in HTML, you first have to link the location of all static files using the static middleware.

app.use(express.static("public"));
  • Here public is the folder in which the static stylesheets are kept.

  • now we can link the CSS with relative path from "public".

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <!-- Add the link to the CSS stylesheet here -->
        <link href="styles/main.css" rel="stylesheet" />
        <!-- Hint: the link is relative to the public folder -->
        <title>Band Generator</title>
    </head>

    <body>
        <main>
  • For the footer we'll have copyright and the year.

  • For the year, as we need it to be always upto date we can use a simple js script in the ejs file to do this as below.

</main>

<footer>
  <p>Copyright © <%=new Date().getFullYear()%></p>
</footer>
</body>

</html>

index.ejs

  • Now for the body we will have an h1 and a button, simple.

  • As its EJS we can make it dynamic i.e. we dont need two different HTML files one for the welcome and one for after you generate the name.

  • Instead, you'll first check if the name has been generated, with locals.name and and an if statement.

<% if (locals.name) {%>
<h1><%= name %></h1>
<%}else{%>
<h1>Welcome to the Band Generator 🤟</h1>
<%}%>
  • If name does not exist we simply make the h1 "Welcome to band generator".

  • if it does we'll make the h1 the randomly generated name.

<%- include("partials/header.ejs") %>

<% if (locals.name) {%>
<h1><%= name %></h1>
<%}else{%>
<h1>Welcome to the Band Generator 🤟</h1>
<%}%>

<form action="/submit" method="POST">
    <input type="submit" value="Generate Name" />
</form>

<%- include("partials/footer.ejs") %>

Index.js

  • Time for the index.js that ties all of them together.

  • we import express and bodyparser.

  • and use bodyparser and static middleware.

import express from "express";
import bodyParser from "body-parser";

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static("public"));
  • We first listen to port 3000, and then add a get method for "/" and post method for "/submit".

  • for the the get method we simply render the index.ejs

app.get("/", (req, res) => {
    res.render("index.ejs");
});
  • For the post method we use the Math.random method to get a random name from the list of adjectives and nouns i got.

  • we then render the index.ejs file but this time we pass in the name variable.

app.post("/submit", (req, res) => {
    var adjNum = Math.floor(Math.random() * adj.length);
    var nounNum = Math.floor(Math.random() * noun.length);
    const bandName = adj[adjNum] + " " + noun[nounNum];
    res.render("index.ejs", {
        name: bandName,
    });

});

Whats going on here?

  • When you first load into the web app you give a get request for "/", so according to the code it returns and renders the index.ejs file.

  • The index.ejs includes header and footer and the top and bottom respectively which when rendered gives a full HTML.

  • In the GET request as there was no "name" variable provided if (locals.name) returns false which makes it print the welcome message.

  • But when we click the generate button the button sends a post request with "/submit".

  • This way a name will be generated and passed to the index.ejs hence if (locals.name) returns true and prints the name generated.

Conclusion

Did you find this article valuable?

Support The Journey by becoming a sponsor. Any amount is appreciated!