1.
Given the following code, answer the below questions:
const fs = require('fs');
// Function to append data to a file
const appendData = (file, data, cb) => {
fs.appendFile(file, data, (err) => {
if (err) {
cb(err, null);
console.log('Failed to append data');
} else {
cb(null, 'Data appended successfully');
console.log('Append operation completed');
}
});
}
// Function to read and log the file content
const logFileContent = (file, cb) => {
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
cb(err, null);
console.log('Failed to read file');
} else {
cb(null, data);
console.log('Read operation completed');
}
});
}
// Code starts here
let file = 'logfile.txt';
let contentToAdd = 'New log entry\n';
appendData(file, contentToAdd, (appendErr, appendResult) => {
if (appendErr) {
console.log(`Error during append`);
} else {
console.log(appendResult);
logFileContent(file, (readErr, fileContent) => {
if (readErr) {
console.log(`Error during read`);
} else {
console.log('File content:');
console.log(fileContent);
}
});
}
});
1) If logfile.txt does not exist, and the call to appendFile is successful, what will be printed to the screen when the code is executed?
2) If logfile.txt exists and contains the text "Existing log entry\n", and the call to appendFile is successful, what will be printed to the
screen when the code is executed?
3) If logfile.txt does not exist , and the call to appendFile is not successful, what will be printed to the screen when the code is
executed?
4) If logfile.txt exists (regardless of its content) but the call to readFile is not successful, what will be printed to the screen when the
code is executed?
1. If logfile.txt doesn't exist, then the following will be printed:
Append operation completed
Data appended Successfully
Read operation completed
File Content: New log entry
2. The following will be printed:
Append operation completed
Data appended successfully
Read operation completed
File content:
Existing log entry
New log entry
3. The following will be printed:
Failed to append data
Error during append
4. The following will be printed:
Append operation completed
Data appended successfully
Failed to read file
Error during read
2.
Reference Code
const events = require('events'); //importing the events module
const eventObj = new events.EventEmitter(); //creating the events object
//Write Handlers for odd and even events
let eventHandler1 = ()=>{
console.log('This number is odd');
}
let eventHandler2 = ()=>{
console.log('This number is even');
}
//Add listeners: Associate the handlers to the events
eventObj.on('Odd', eventHandler1);
eventObj.on('Even', eventHandler2);
//Decide on the event that needs to be emitted
let eventName = Number(process.argv[2])%2 === 0? 'Even':'Odd';
eventObj.emit(eventName);
Question
checkHelloWord.js is a Node.js script that accepts a single argument from the command line, which is a string. The script uses
EventEmitter to emit either a "helloFound" or "noHello" event based on whether the word "hello" is found in the provided string. If the
word "hello" is found, emit a "helloFound" event; otherwise, emit a "noHello" event. The script uses two event handlers: one for the
"helloFound" event, which prints "The word 'hello' is found in the provided string", and another for the "noHello" event, which prints
"The word 'hello' is not found in the provided string".
Fill in the blanks below to complete the code for checkHelloWord.js
3.
Reference Code
const fs = require('fs');
let str = 'Append this string \n';
fs.appendFile('new.txt', str, (err)=>{
if (err){
console.log('String cannot be appended');
}else{
console.log('String has been appended');
}
});
Questions
Below is the code for a basic "Hello World" HTTP server written in Node.js.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello, World!\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Update the code for the server such that each time a request arrives at the server, the server counts the number of request received so far and
logs the number of request along with the following information to a log file called info.log
The host name
The request URL
The request method
The request user agent
Answer:
const http = require('http');
const fs = require('fs');
let reqCnt = 0;
const server = http.createServer((req, res) => {
reqCnt++;
let str =
`Request count: ${reqCnt}
Hostname: ${req.headers.hostname}
URL: ${req.url}
Method: ${req.method}
User Agent: ${req.headers['user-agent']}`;
fs.appendFile('new.txt', str, (err) => {
if(err){
res.end('request was not logged');
}else{
res.end('Request has been logged');
}
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
});