Backend Exp 2
Backend Exp 2
1) Aim:
To store the data from our previous experiment (employee salary program) in a file and then use that file in
another program, we can follow these steps:
1. Store Data in a JSON File: Ensure that our main program writes the data to a JSON file
2. Read Data from JSON File in Another Program: Create a new Node.js program that reads the data from the
JSON file and performs some operations on it.
2) Code:
Server.js
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Data.json
[
{
"id": 1,
"name": "satvik",
"age": 22,
"position": "Software Engineer",
"email": "[email protected]"
},
{
"id": 2,
"name": "adarsh",
"age": 22,
"position": "Project Manager",
"email": "[email protected]"
},
{
"id": 3,
"name": "aryan",
"age": 22,
"position": "UX Designer",
"email": "[email protected]"
}
]
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Employee Data</title>
</head>
<body>
<h1>Employee Data Management system</h1>
<button id="loadDataButton">Load Employee Data</button>
<div id="employees"></div>
<script>
function loadEmployeeData() {
fetch("http://localhost:3000/data")
.then((response) => response.json())
.then((employees) => {
const employeesDiv = document.getElementById("employees");
employeesDiv.innerHTML = "";
employees.forEach((employee) => {
const employeeDiv = document.createElement("div");
employeeDiv.className = "employee";
employeeDiv.innerHTML = `
<h2>${employee.name}</h2>
<p><strong>ID:</strong> ${employee.id}</p>
<p><strong>Age:</strong> ${employee.age}</p>
<p><strong>Position:</strong> ${employee.position}</p>
<p><strong>Email:</strong> ${employee.email}</p>
`;
employeesDiv.appendChild(employeeDiv);
});
})
.catch((error) => console.error("Error:", error));
}
document
.getElementById("loadDataButton")
.addEventListener("click", loadEmployeeData);
</script>
</body>
</html>
3) Output:
Learning outcomes