How to build Love Calculator using Node.js ?
Last Updated :
24 Jul, 2024
In this article, we are going to create a Love Calculator. A Love Calculator is used to calculate the love percentage between the partners.
Functionality:
- Take User’s Name
- Take User’s Partner Name
- Show the Love Percentage
Approach: We are going to use Body Parser by which we can capture user input values from the form such as the user’s name, and the user’s partner name Then we will calculate the percentage from them and send the patients’ data to the web page using EJS. EJS is a middleware that makes it easy to send data from your server file (app.js or server.js) to a web page.
Implementation: Below is the step-by-step implementation of the above approach.
Step 1: Project Setup
Initializes NPM: Create and Locate your project folder into the terminal & type the command
npm init -y
It initializes our node application & makes a package.json file.
Install Dependencies: Locate your root project directory into the terminal and type the command
npm install express ejs
To install Express, and Ejs as dependencies inside your project
Create Server File: Create an ‘app.js’ file, inside this file require the Express Module, and create a constant ‘app’ for creating an instance of the express module, then set the EJS as the default view engine.
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
Rearrange Your Directories: It is required to use ‘.ejs’ as an extension for the HTML file instead of ‘.html’ for using EJS inside it. Then you have to move every ‘.ejs’ file in the views directory inside your root directory. EJS is by default looking for ‘.ejs’ files inside the views folder.
Use EJS variable: Create a ‘home.ejs’, inside the ‘home.ejs’ you have to use EJS Variables to receive values from your server file. You can declare variables in EJS like
<%= variableName %>
HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<%= variableName %>
</body>
</html>
Send data to a variable: Inside your server file ( app.js or index.js ), you can send an EJS file along with some data by using the render method.
app.get("/", (req, res) => {
res.render("home", { variableName: "Hello Geeks!" })
})
JavaScript
const express = require('express')
const app = express()
app.set('view engine', 'ejs')
app.get("/", (req, res) => {
res.render("home", { variableName: "Hello Geeks!" })
})
app.listen(3000, (req, res) => {
console.log("App is running on port 3000")
})
Fetching data from form to app.js: To receive input values of a form, we have to use a node package named body-parser.
Install body-parser:
npm install body-parser
Require body-parser module:
const bodyParser = require('body-parser')
And then:
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
Then we can handle form data using the request object.
Step 2: Create Functionalities:
Take User’s Name and User’s Partner Name: For this, we have to create a form inside ‘home.ejs’ file and handle the form data inside our ‘app.js’ file using Body Parser.
<form action="/" method="post">
<input type="text" name="username" placeholder="Your Name">
<input type="text" name="partnername" placeholder="Your Partner Name">
<button type="submit">Calculator</button>
</form>
Handle form data inside ‘app.js’: We have to fetch values from a form using req.body.valueName, and then perform the operation shown below to calculate a value as a percentage.
app.post('/', (req, res)=> {
userName = req.body.username;
partnerName = req.body.partnername;
var combinedNames = userName + partnerName
var lowerNames = combinedNames.toLowerCase()
console.log(lowerNames);
var t = lowerNames.split("t").length - 1;
var r = lowerNames.split("r").length - 1;
var u = lowerNames.split("u").length - 1;
var e = lowerNames.split("e").length - 1;
var firstDigit = t + r + u + e
if (firstDigit < 5) {
firstDigit = firstDigit + 5;
}
var l = lowerNames.split("l").length - 1;
var o = lowerNames.split("o").length - 1;
var v = lowerNames.split("v").length - 1;
var e = lowerNames.split("e").length - 1;
var secondDigit = l + o + v + e
var lovePercentage = firstDigit + '' + secondDigit;
});
Send Value to the ‘home.ejs’ page: As in the previous step we send a string “Hello Geeks!” to the home page, now let’s send the percentage value to a variable ‘lovePercentage’.
res.render("home.ejs", {percentage: lovePercentage});
Receive Value of lovePercentage: To Receive the value sent from the ‘app.js’ we have to use ejs variable inside ‘home.ejs’.
<p>Love Percentage: <%= percentage %></p>
Below is the complete code to build Love Calculator using Node.js:
app.js
JavaScript
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
const bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.render("home.ejs", {percentage: ""});
});
app.post('/', (req, res)=> {
userName = req.body.username;
partnerName = req.body.partnername;
var combinedNames = userName + partnerName
var lowerNames = combinedNames.toLowerCase()
console.log(lowerNames);
var t = lowerNames.split("t").length - 1;
var r = lowerNames.split("r").length - 1;
var u = lowerNames.split("u").length - 1;
var e = lowerNames.split("e").length - 1;
var firstDigit = t + r + u + e
if (firstDigit < 5) {
firstDigit = firstDigit + 5;
}
var l = lowerNames.split("l").length - 1;
var o = lowerNames.split("o").length - 1;
var v = lowerNames.split("v").length - 1;
var e = lowerNames.split("e").length - 1;
var secondDigit = l + o + v + e
var lovePercentage = firstDigit + '' + secondDigit;
res.render("home.ejs", {percentage: lovePercentage});
});
app.listen(3000);
home.ejs
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Love Calculator</title>
</head>
<body>
<form action="/" method="post">
<input type="text" name="username"
placeholder="Your Name">
<input type="text" name="partnername"
placeholder="Your Partner Name">
<button type="submit">Calculator</button>
</form>
<p>Love Percentage: <%= percentage %></p>
</body>
</html>
Steps to run the application: Inside the terminal type the command to run your script.
node app.js
Output:
Similar Reads
Build a Loan Calculator using Next.js
The Loan Calculator allows users to determine loan amount, interest rate, and tenure, calculate monthly mortgage payments, total loan payments over tenure, and total interest payable. In this article, we will walk you through the process of building a Loan Calculator using Next.js. Let's take a look
4 min read
BMI Calculator Using React
In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese. Output Previ
3 min read
Age Calculator Using React-JS
In this article, we will create an Age Calculator using ReactJS and Bootstrap. This free age calculator computes age in terms of years, months, weeks, days, hours, minutes, and seconds, given a date of birth. Users can now input their birth year and calculate their current age with just a few clicks
4 min read
How to Get Data from MongoDB using Node.js?
One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 min read
How to Add Data in JSON File using Node.js ?
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
BMI Calculator using Express.js
The Body Mass Index(BMI) is represented in terms of weight and height of an individual. It is the ratio of the weight of the body to the square of the height of the body in kilograms and meters respectively. BMI = (weight of body) / (height of body)2 Unit of weight: Kilogram(Kg); Unit of height: Met
3 min read
Create a Calculator App Using Next JS
Creating a Calculator app is one of the basic projects that clears the core concept of a technology. In this tutorial, we'll walk you through the process of building a calculator app using Next.js. Output Preview: Let us have a look at how the final output will look like. Prerequisites:NPM & Nod
3 min read
How to Create Sentiment Analysis Application using Node.js ?
Sentiment Analysis is a natural language processing technique used to determine emotions from textual data. It's often performed to know customer requirements, study product sentiment in user feedback, decision-making, and more. Types of Sentiment Analysis: Fine-grained Sentiment Analysis: It is don
10 min read
How to write code using module.exports in Node.js ?
module is a discrete program, contained in a single file in Node.js. They are tied to files with one module per file. module.exports is an object that the current module returns when it is "required" in another program or module. We are going to see a simple code like the calculator to learn how to
3 min read
How to write âBeautiful Lifeâ in Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and itâs not a programming language. Most people are confused and understand itâs a framework or a programming language. We often use
1 min read