The current code reads a JSON file, parses it into an object, and then logs certain values to the console. We’ll go through the steps to make this code more flexible by allowing it to handle a JSON object.
Here’s the code as it stands:
const http = require('http');
const fs = require('fs');
const site = http.createServer(function(req, res) {
fs.readFile('test.json', function(error, data) {
let holder = JSON.parse(data);
res.setHeader('Content-Type', 'application/json');
console.log(holder.firstName + ' ' + holder.lastName);
res.write(data);
res.end();
});
});
site.listen(3000);
Current Functionality
This code does the following:
- Creates a basic HTTP server: The server listens on port 3000.
- Reads a JSON file (
test.json
): When a request is made, it reads the filetest.json
. - Parses the JSON file: The content of the file is parsed into a JavaScript object.
- Logs specific properties (
firstName
andlastName
): It logs these properties to the console. - Responds with the JSON data: The server responds with the JSON content in the HTTP response.
Goal: Modify the Code to Handle a JSON Object
To make the code more flexible and capable of handling any JSON object, we’ll need to:
- Allow the server to read any JSON object from the file.
- Access the properties of this object dynamically instead of hardcoding the properties (
firstName
andlastName
). - Provide a more dynamic console output based on the properties available in the JSON file.
Step-by-Step Modifications
1. Check for JSON File and Read It
We will start by ensuring that the JSON file exists and reading its contents:
fs.readFile('test.json', 'utf8', function(error, data) {
if (error) {
console.error('Error reading the file:', error);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
let holder;
try {
holder = JSON.parse(data);
} catch (e) {
console.error('Error parsing JSON:', e);
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad Request');
return;
}
// Further code to handle the JSON object
});
2. Access Properties Dynamically
Instead of hardcoding the properties, we’ll loop through the object properties and log them dynamically:
for (let key in holder) {
if (holder.hasOwnProperty(key)) {
console.log(`${key}: ${holder[key]}`);
}
}
This loop will iterate over each key in the object and log the key-value pair to the console.
3. Respond with JSON Data
We’ll keep the part of the code that sets the response header and writes the data back to the client:
res.setHeader('Content-Type', 'application/json');
res.write(data);
res.end();
Final Code
Here’s how the complete modified code looks:
const http = require('http');
const fs = require('fs');
const site = http.createServer(function(req, res) {
fs.readFile('test.json', 'utf8', function(error, data) {
if (error) {
console.error('Error reading the file:', error);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
let holder;
try {
holder = JSON.parse(data);
} catch (e) {
console.error('Error parsing JSON:', e);
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad Request');
return;
}
// Dynamically log the object properties
for (let key in holder) {
if (holder.hasOwnProperty(key)) {
console.log(`${key}: ${holder[key]}`);
}
}
res.setHeader('Content-Type', 'application/json');
res.write(data);
res.end();
});
});
site.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Key Takeaways
- Dynamic Property Handling: By iterating over the object properties, your server code becomes flexible enough to handle any JSON structure without requiring changes.
- Error Handling: It’s crucial to handle errors effectively, both in reading the file and parsing JSON, to ensure the server can respond appropriately to any issues.
- Server Response: The code sends back the JSON content to the client, maintaining the original functionality while making the logging dynamic.
This modification makes the server more robust and adaptable to changes in the JSON structure, ensuring that it can handle any well-formed JSON object you throw at it.
