Employee Data Management System with IP Classification
This tutorial walks through creating a Node.js application that manages employee data with IP address classification. We'll generate test data, categorize employees by IP class, and implement various data operations.
1. Generate Employee Data
a. Using Mockaroo for Test Data
- Visit www.mockaroo.com
- Create a dataset with at least 7,000 employee records
b. Required Fields
Fields to include: • id (integer, unique, auto-incrementing) • fullName (string, e.g., "John Doe") • email (string, e.g., "xyz.abc@example.com") • department (string, e.g., "Engineering") • ipAddress (IPv4 address, e.g., "192.168.1.45") • company (custom string field, e.g., "TechCorp")
c. Save the Data
Save the generated data as employees.json
in your project directory.
2. IP Address Classification System
IP Class | Range | Example | API Endpoint |
---|---|---|---|
Class A | 1-126 | 10.0.0.1 | /api/employees/classA |
Class B | 128-191 | 172.16.0.1 | /api/employees/classB |
Class C | 192-223 | 192.168.0.1 | /api/employees/classC |
Class D | 224-239 | 224.0.0.1 | /api/employees/classD |
Class E | 240-255 | 240.0.0.1 | /api/employees/classE |
Implementation Requirements:
- Use Node.js with the
fs
module to read fromemployees.json
- Filter data for each IP class
- Return results as JSON through API endpoints
Next Steps
After implementing the basic classification system, you can extend it with additional features like:
- Deleting employees by IP class
- Updating employee information
- Adding new employees with duplicate checking
const fs = require('fs');
const http = require('http');
const url = require('url');
function filterIP(data, min, max) {
return data.filter(item => {
let firstOctet = parseInt(item.ip_address.split('.')[0]);
return firstOctet >= min && firstOctet <= max;
});
}
function delClassE(data) {
fs.unlinkSync('./files/classE.json');
data.filter(item => {
const firstOctet = parseInt(item.ip_address.split('.')[0]);
if(!(firstOctet >= 240 && firstOctet<=255)){
return item;
}
})
}
function updateClassD() {
let rawData = fs.readFileSync('./files/ClassD.json', 'utf-8');
let data = JSON.parse(rawData);
return data.filter(item => {
item.company = 'XYZ Corp';
return item;
})
}
function insertNewEmp(employeesData) {
let rawData = fs.readFileSync('new100.json', 'utf-8');
let data = JSON.parse(rawData);
for (i = 0; i < data.length; i++) {
for (j = 0; j < employeesData.length; j++) {
if (data[i].id === employeesData[j].id) {
console.log("Duplicate ID Found - Insertion not Possible " + data[i].id + " = " + employeesData[j].id);
break;
}
}
employeesData.push(data[i]);
console.log("Insertion Possible ");
}
return employeesData;
}
const server = http.createServer((req, res) => {
if (req.url === '/favicon.ico') {
res.end();
return;
}
const employeesData = require('./employees.json');
const myURL = url.parse(req.url, true);
let max, min, filterData;
switch (myURL.pathname) {
case '/':
const menu = `
This is Homepage. These are the valid URLs:
- /
- /api/employees/classA
- /api/employees/classB
- /api/employees/classC
- /api/employees/retClassC
- /api/employees/classD
- /api/employees/classE
- /api/employees/deleteClassE
- /api/employees/updateClassD
- /api/employees/insertNewEmp
`;
res.end(menu);
break;
case '/api/employees/classA':
min = 1;
max = 127;
filterData = filterIP(employeesData, min, max);
fs.writeFileSync('./files/classA.json', JSON.stringify(filterData));
res.end(JSON.stringify(filterData));
break;
case '/api/employees/classB':
min = 128;
max = 191;
filterData = filterIP(employeesData, min, max);
fs.writeFileSync('./files/classB.json', JSON.stringify(filterData));
res.end(JSON.stringify(filterData));
break;
case '/api/employees/classC':
min = 192;
max = 223;
filterData = filterIP(employeesData, min, max);
fs.writeFileSync('./files/classC.json', JSON.stringify(filterData));
res.end(JSON.stringify(filterData));
break;
case '/api/employees/retClassC':
try {
const classCData = fs.readFileSync('./files/classC.json', 'utf-8');
res.end(classCData);
} catch (err) {
res.statusCode = 500;
res.end('Error reading Class C data');
}
break;
case '/api/employees/classD':
min = 224;
max = 239;
filterData = filterIP(employeesData, min, max);
fs.writeFileSync('./files/classD.json', JSON.stringify(filterData));
res.end(JSON.stringify(filterData));
break;
case '/api/employees/classE':
min = 240;
max = 255;
filterData = filterIP(employeesData, min, max);
fs.writeFileSync('./files/classE.json', JSON.stringify(filterData));
res.end(JSON.stringify(filterData));
break;
case '/api/employees/deleteClassE':
delClassE();
res.end("Class E Data Deleted Successfully");
break;
case '/api/employees/updateClassD':
let result = updateClassD();
fs.writeFileSync('./files/classD.json', JSON.stringify(result));
res.end(JSON.stringify(result));
break;
case '/api/employees/insertNewEmp':
let newData = insertNewEmp(employeesData);
fs.appendFileSync('employees.json', JSON.stringify(newData));
res.end(`inserted data`);
break;
default:
res.statusCode = 404;
res.end('Route not found');
}
});
server.listen(8080, () => {
console.log("Server Running at Port 8080");
});
Node.js Web Server Challenge: Build a Logging System with HTTP Routes
🚀 Task Overview
Your challenge is to create a Node.js web server using the built-in http
module. The server should handle multiple routes, log visits to a file, and store data from query parameters in separate text files.
🎯 Requirements
1. Set Up the Server
- Use the
http
module to create a server. - Listen on a port of your choice (e.g.,
3000
or8080
).
2. Define Routes
Your server should handle the following routes:
/
→ Home route (simple response)/users
→ Store user data from query parameters inusers.txt
/products
→ Store product data from query parameters inproducts.txt
/books
→ Store book data from query parameters inbooks.txt
/display
→ Optional: Display logs or file contents
3. Log Every Visit
- Create a
log.txt
file that records:- Serial number (can be timestamp or counter)
- Date & time of visit
- URL visited
- Number of query parameters received
4. Store Data from Query Parameters
users.txt
→ Should store:id
,name
,age
,city
,university
(from/users
route)
products.txt
→ Should store:id
,title
,price
(from/products
route)
books.txt
→ Should store:id
,title
,edition
,year
,press
(from/books
route)
5. Test Your Server
Hit at least 5 different URLs with query parameters to verify functionality. Examples:
/
/users?id=24&name=Abdullah&age=60&city=Islamabad&uni=QAU
/products?id=89&title=Samsung&price=75K
/books?id=19&title=AlgorithmDesignAndApplications&edition=3&year=2019&press=Wiley
/display
(optional)
📌 Bonus Challenge (Optional)
- Add error handling for missing query parameters.
- Format the log entries in a readable way (e.g., JSON, CSV).
- Display the contents of log files when hitting
/display
.
💡 Tips
- Use
fs.appendFileSync()
orfs.appendFile()
for logging. - Parse query parameters using the
url
module. - Ensure files are created if they don't exist.
🔗 Share Your Solution!
Once you complete the challenge, share your code in the comments or on social media with #NodeJSTask. Let's see who builds the best logging system! 🚀
Happy Coding! 😊
const http = require('http');
const url = require('url');
const fs = require('fs');
const now = new Date();
let data;
const server = http.createServer((request, response) => {
if (request.url === "/favicon.ico") {
return response.end();
}
const today = new Date();
const myURL = url.parse(request.url, true);
const query = myURL.query;
const logEntry = {
serialNo: today,
date: `${now.getDate()} / ${now.getMonth() + 1} / ${now.getFullYear()}`,
time: `${now.getHours()} : ${now.getMinutes()} : ${now.getSeconds()}`,
path: request.url,
queryParams: Object.keys(query).length
};
fs.appendFileSync("log.txt", JSON.stringify(logEntry) + '\n');
if (myURL.pathname == "/") {
data = `http://localhost:8080/
http://localhost:8080/users?id=24&name=Abdullah&age=60&city=Islamabad&uni=QAU
http://localhost:8080/products?id=89&title=Samsung&price=75K
http://localhost:8080/books?id=19&title=AlgorithmDesignAndApplications&edition=3&year=2019&press=Wiley
http://localhost:8080/display`;
}
else if (myURL.pathname == "/users") {
const userData = {
id: query.id,
name: query.name,
age: query.age,
city: query.city,
university: query.uni
};
fs.appendFileSync("users.txt", JSON.stringify(userData) + '\n');
data = "User data recorded";
}
else if (myURL.pathname == "/products") {
const productData = {
id: query.id,
title: query.title,
price: query.price
};
fs.appendFileSync("products.txt", JSON.stringify(productData) + '\n');
data = "Product data recorded";
}
else if (myURL.pathname == "/books") {
const bookData = {
id: query.id,
title: query.title,
edition: query.edition,
year: query.year,
press: query.press
};
fs.appendFileSync("books.txt", JSON.stringify(bookData) + '\n');
data = "Book data recorded";
}
else if (myURL.pathname == "/display") {
try {
const logContent = fs.readFileSync("log.txt", "utf8");
const usersContent = fs.readFileSync("users.txt", "utf8");
const productsContent = fs.readFileSync("products.txt", "utf8");
const booksContent = fs.readFileSync("books.txt", "utf8");
data = `Logs:\n${logContent}\n\nUsers:\n${usersContent}\n\nProducts:\n${productsContent}\n\nBooks:\n${booksContent}`;
} catch (err) {
data = "Error reading files";
}
}
else {
data = "Error 404 No Page Found";
}
response.end(data);
});
['log.txt', 'users.txt', 'products.txt', 'books.txt'].forEach(file => {
if (!fs.existsSync(file)) {
fs.writeFileSync(file, '');
}
});
server.listen(8080, () => {
console.log("***Server Started***");
});
0 Comments