Experiment No. 6- Design Homepage using Nodejs.
Steps to Create a Home Page
Initialize a New Node.js Project
Open a terminal and create a new directory for your project. Navigate into the
directory and run npm init to initialize a new Node.js project.
mkdir my-homepage
cd my-homepage
npm init -y
Install Express
Install the express package, which is a minimal and flexible Node.js web application
framework.
npm install express
Create the Server
Create a file named server.js in your project directory.
// server.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Route for the home page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Create the Home Page HTML
Create a directory named public in your project directory. Inside this directory, create a file
named index.html.
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.container {
text-align: center;
}
h1 {
color: #333;
}
p {
color: #555;
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to My Home Page</h1>
<p>This is a simple home page created with Node.js and Express.</p>
</div>
</body>
</html>
Run the Server
In the terminal, run the server using Node.js.
node server.js
View the Home Page
Open your web browser and navigate to http://localhost:3000. You should see your
home page with the content from index.html.