Tuesday, 21 January 2025

Lecture notes Of Class 5: Understanding Callbacks in Node.js

 

Lecture notes Of Class 5: Understanding Callbacks in Node.js


Objective:

In this class, you will learn about asynchronous programming in Node.js, focusing on callbacks. You will understand how Node.js handles I/O operations and how callbacks are used to handle asynchronous tasks.


Introduction to Asynchronous Programming

Node.js is built on an asynchronous programming model, which allows non-blocking operations. This is in contrast to the traditional synchronous model, where each operation waits for the previous one to complete before moving on.

In synchronous code, one operation runs after the other, and the program halts until the current operation is complete. However, asynchronous code does not wait for a task to complete and moves to the next task immediately, improving performance, especially in I/O-heavy applications like web servers.


What are Callbacks?

A callback is a function that is passed as an argument to another function and is executed later when a certain task or event is completed. In Node.js, callbacks are used extensively to handle asynchronous operations like file reading, network requests, database queries, and more.

When an asynchronous function completes, the callback function is invoked with the result of that operation (or an error, if something went wrong).

Example of a simple callback:

javascript

CopyEdit

function greet(name, callback) {

  console.log("Hello, " + name);

  callback();

}

 

function sayGoodbye() {

  console.log("Goodbye!");

}

 

greet("Alice", sayGoodbye);

Output:

CopyEdit

Hello, Alice

Goodbye!

In this example:

  • greet() accepts a callback function (sayGoodbye) and executes it after logging a greeting message.

Why are Callbacks Important in Node.js?

In Node.js, callbacks are crucial because many operations like file reading, querying databases, and HTTP requests are asynchronous. Without callbacks, these operations would block the execution of the program, leading to delays in responding to users or processing tasks.

Callbacks allow Node.js to handle multiple tasks simultaneously, making it efficient for I/O-bound tasks.


How Callbacks Work in Node.js

Let’s take a look at an asynchronous file operation using the fs (file system) module. When reading a file in a synchronous manner, the program would halt until the file is read. But with callbacks, Node.js can continue executing the program while the file is being read, and only call the callback function once the reading is completed.

Here’s an example of reading a file asynchronously using callbacks:

javascript

CopyEdit

const fs = require('fs');

 

// Asynchronous file read

fs.readFile('example.txt', 'utf8', function(err, data) {

  if (err) {

    console.log("Error reading the file:", err);

    return;

  }

  console.log("File content:", data);

});

console.log("File reading initiated...");

In this example:

  • fs.readFile() is an asynchronous function that reads the contents of the file 'example.txt'.
  • It accepts a callback that is invoked once the file has been read.
  • The callback handles two parameters: err (for any errors) and data (the content of the file).
  • The message "File reading initiated..." is logged before the file is read, demonstrating the non-blocking nature of the program.

Error Handling in Callbacks

In Node.js, the first argument of a callback function is typically reserved for an error object. If no error occurs, the argument is null. If an error occurs, the error object contains details about the problem.

For example:

javascript

CopyEdit

fs.readFile('nonexistentfile.txt', 'utf8', function(err, data) {

  if (err) {

    console.log("Error:", err.message);

    return;

  }

  console.log("File content:", data);

});

In this case, if the file doesn't exist, the error message will be printed instead of the file content.


Callback Hell (Pyramid of Doom)

One issue with using callbacks extensively in asynchronous operations is the possibility of callback hell (also known as the pyramid of doom). This happens when callbacks are nested inside one another, resulting in deeply indented, hard-to-maintain code.

Example of callback hell:

javascript

CopyEdit

fs.readFile('file1.txt', 'utf8', function(err, data1) {

  if (err) return console.log(err);

  fs.readFile('file2.txt', 'utf8', function(err, data2) {

    if (err) return console.log(err);

    fs.readFile('file3.txt', 'utf8', function(err, data3) {

      if (err) return console.log(err);

      console.log(data1, data2, data3);

    });

  });

});

While this works, the code becomes hard to read and maintain. This issue can be mitigated by using Promises or async/await, which will be covered in later classes.


Lab Tasks


Task 1: Implement a Callback Function in a Node.js Script

Create a script that simulates a task (like fetching data from a database) and then uses a callback function to return the result once the task is done.

Example:

javascript

CopyEdit

function fetchData(callback) {

  setTimeout(() => {

    console.log("Data fetched from database!");

    callback("Data");

  }, 2000);

}

 

fetchData(function(result) {

  console.log("Callback received:", result);

});

In this example:

  • The fetchData function simulates a delayed operation using setTimeout().
  • Once the data is fetched, the callback function is invoked with the result.

Task 2: Use Callbacks to Handle Asynchronous File Operations

Write a script that reads two files asynchronously using the fs.readFile() method and then logs the content of both files once they have been read.

Example:

javascript

CopyEdit

const fs = require('fs');

 

fs.readFile('file1.txt', 'utf8', function(err, data1) {

  if (err) {

    console.log("Error reading file1:", err);

    return;

  }

  console.log("File1 content:", data1);

 

  fs.readFile('file2.txt', 'utf8', function(err, data2) {

    if (err) {

      console.log("Error reading file2:", err);

      return;

    }

    console.log("File2 content:", data2);

  });

});

In this example:

  • The program reads the contents of two files asynchronously.
  • It uses callbacks to handle the contents of the files once they have been read.

Conclusion

Callbacks are essential for handling asynchronous operations in Node.js. They allow the program to continue executing while waiting for I/O tasks to complete, which is critical for building efficient, non-blocking applications. Although callback hell can occur with deeply nested callbacks, this can be managed with proper design, and more advanced techniques like Promises or async/await will help simplify asynchronous code.

4o mini

You said:

write 10 no of assignments with solution in detail from the same above topic

ChatGPT said:

ChatGPT

Assignments on Understanding Callbacks in Node.js


Assignment 1: Basic Callback Function

Problem:
Write a Node.js program that accepts a name and age, and then displays a message after a 2-second delay using a callback function.

Solution:

javascript

CopyEdit

function displayInfo(name, age, callback) {

  setTimeout(() => {

    console.log(`Name: ${name}, Age: ${age}`);

    callback();

  }, 2000);

}

 

function afterDisplay() {

  console.log("Information displayed successfully!");

}

 

displayInfo("Alice", 25, afterDisplay);

Explanation:

  • The displayInfo function accepts name, age, and a callback function.
  • The setTimeout simulates an asynchronous delay of 2 seconds.
  • Once the information is displayed, the callback (afterDisplay) is called.

Assignment 2: Simple File Read Operation with Callback

Problem:
Write a program that reads a file asynchronously using the fs.readFile() method and logs its contents using a callback function.

Solution:

javascript

CopyEdit

const fs = require('fs');

 

fs.readFile('example.txt', 'utf8', (err, data) => {

  if (err) {

    console.log("Error reading file:", err);

    return;

  }

  console.log("File Content: ", data);

});

Explanation:

  • The fs.readFile() method is used to read a file asynchronously.
  • The callback function is invoked once the file reading operation completes, either with an error or the data.

Assignment 3: Callback for Multiple File Reads

Problem:
Write a Node.js program that reads two files asynchronously and displays the content of both files using callbacks.

Solution:

javascript

CopyEdit

const fs = require('fs');

 

fs.readFile('file1.txt', 'utf8', (err, data1) => {

  if (err) {

    console.log("Error reading file1:", err);

    return;

  }

  console.log("File1 Content:", data1);

 

  fs.readFile('file2.txt', 'utf8', (err, data2) => {

    if (err) {

      console.log("Error reading file2:", err);

      return;

    }

    console.log("File2 Content:", data2);

  });

});

Explanation:

  • The program reads two files, and the callback is used to handle the contents of each file.
  • The second file is read only after the first one completes.

Assignment 4: Handling Errors in Callbacks

Problem:
Modify the previous example to handle errors properly in callbacks. If the file doesn't exist, log a custom error message.

Solution:

javascript

CopyEdit

const fs = require('fs');

 

fs.readFile('file1.txt', 'utf8', (err, data1) => {

  if (err) {

    console.log("Error reading file1: File not found.");

    return;

  }

  console.log("File1 Content:", data1);

 

  fs.readFile('file2.txt', 'utf8', (err, data2) => {

    if (err) {

      console.log("Error reading file2: File not found.");

      return;

    }

    console.log("File2 Content:", data2);

  });

});

Explanation:

  • The if (err) block checks if an error occurs and handles it with a custom message.

Assignment 5: Callback with SetTimeout

Problem:
Write a Node.js program that uses a callback function to print a message after a delay of 3 seconds.

Solution:

javascript

CopyEdit

function delayedMessage(callback) {

  setTimeout(() => {

    callback("Message displayed after 3 seconds");

  }, 3000);

}

 

delayedMessage((message) => {

  console.log(message);

});

Explanation:

  • The delayedMessage function accepts a callback, which is invoked after 3 seconds.
  • The callback prints the message when called.

Assignment 6: Simulating an Asynchronous Task

Problem:
Create a function processData that simulates fetching data from a database. Use a callback to return the result after a 2-second delay.

Solution:

javascript

CopyEdit

function processData(callback) {

  setTimeout(() => {

    const data = { user: "John Doe", age: 30 };

    callback(null, data);

  }, 2000);

}

 

processData((err, data) => {

  if (err) {

    console.log("Error:", err);

    return;

  }

  console.log("Data received:", data);

});

Explanation:

  • processData simulates fetching data from a database with a delay of 2 seconds.
  • The callback handles the data or an error if one occurs.

Assignment 7: Simple Calculator with Callbacks

Problem:
Write a calculator function that takes two numbers and an operation (add, subtract, multiply, divide) and uses a callback to return the result.

Solution:

javascript

CopyEdit

function calculator(num1, num2, operation, callback) {

  setTimeout(() => {

    let result;

    switch (operation) {

      case 'add':

        result = num1 + num2;

        break;

      case 'subtract':

        result = num1 - num2;

        break;

      case 'multiply':

        result = num1 * num2;

        break;

      case 'divide':

        if (num2 === 0) {

          callback("Error: Cannot divide by zero");

          return;

        }

        result = num1 / num2;

        break;

      default:

        callback("Error: Invalid operation");

        return;

    }

    callback(null, result);

  }, 1000);

}

 

calculator(10, 5, 'add', (err, result) => {

  if (err) {

    console.log(err);

    return;

  }

  console.log("Result:", result);

});

Explanation:

  • The calculator function accepts two numbers and an operation.
  • It uses setTimeout to simulate the delay and performs the calculation. The result is passed to the callback function.

Assignment 8: Asynchronous Task Queue

Problem:
Write a program that executes three tasks sequentially with callbacks (each task takes 2 seconds), logging "Task completed" after each.

Solution:

javascript

CopyEdit

function task1(callback) {

  setTimeout(() => {

    console.log("Task 1 completed");

    callback();

  }, 2000);

}

 

function task2(callback) {

  setTimeout(() => {

    console.log("Task 2 completed");

    callback();

  }, 2000);

}

 

function task3(callback) {

  setTimeout(() => {

    console.log("Task 3 completed");

    callback();

  }, 2000);

}

 

task1(() => {

  task2(() => {

    task3(() => {

      console.log("All tasks completed!");

    });

  });

});

Explanation:

  • Each task function has a callback that triggers the next task once the current one completes.
  • This demonstrates sequential execution of asynchronous tasks.

Assignment 9: Reading Multiple Files with Nested Callbacks

Problem:
Write a program that reads three files sequentially and displays their contents using nested callbacks.

Solution:

javascript

CopyEdit

const fs = require('fs');

 

fs.readFile('file1.txt', 'utf8', (err, data1) => {

  if (err) return console.log("Error reading file1:", err);

  console.log("File1 Content:", data1);

 

  fs.readFile('file2.txt', 'utf8', (err, data2) => {

    if (err) return console.log("Error reading file2:", err);

    console.log("File2 Content:", data2);

 

    fs.readFile('file3.txt', 'utf8', (err, data3) => {

      if (err) return console.log("Error reading file3:", err);

      console.log("File3 Content:", data3);

    });

  });

});

Explanation:

  • The program reads three files sequentially, where each file is read inside the callback of the previous one.

Assignment 10: Callback for Network Request

Problem:
Simulate a network request using setTimeout and use a callback to handle the response after a 3-second delay.

Solution:

javascript

CopyEdit

function networkRequest(url, callback) {

  setTimeout(() => {

    const response = `Response from ${url}`;

    callback(null, response);

  }, 3000);

}

 

networkRequest("http://example.com", (err, response) => {

  if (err) {

    console.log("Error:", err);

    return;

  }

  console.log(response);

});

Explanation:

  • The networkRequest function simulates a network request with a 3-second delay.
  • Once the "response" is ready, the callback handles it.

Conclusion

These assignments demonstrate the versatility of callbacks in handling asynchronous tasks in Node.js. Callbacks help manage operations such as file reading, network requests, and computations efficiently without blocking the main thread. Proper error handling and sequential task execution using callbacks are fundamental skills for every Node.js developer.

4o mini

You said:

write 100 no of MCQ answer with explanation from the same above topic

ChatGPT said:

ChatGPT

Here’s a set of 100 MCQs based on the topic Understanding Callbacks in Node.js with answers and detailed explanations. These questions cover the basic concepts of callbacks, asynchronous programming, and error handling in Node.js.


Multiple Choice Questions (MCQs)


1. What is a callback in Node.js?

a) A function that is passed as an argument to another function and is executed after a task is completed.
b) A function that executes immediately.
c) A function that returns a promise.
d) A function that executes during an event loop.

Answer: a) A function that is passed as an argument to another function and is executed after a task is completed.

Explanation: A callback is a function that is passed into another function as an argument and is executed once that function completes its task.


2. How does Node.js handle asynchronous operations?

a) Using callbacks
b) Using synchronous methods only
c) Using promises
d) Using blocking operations

Answer: a) Using callbacks

Explanation: Node.js uses callbacks to handle asynchronous operations like reading files, making network requests, etc., so the event loop doesn’t block other operations.


3. What method in Node.js uses callbacks for asynchronous file reading?

a) fs.writeFile
b) fs.readFile
c) fs.appendFile
d) fs.open

Answer: b) fs.readFile

Explanation: fs.readFile() is an asynchronous method in Node.js, and it accepts a callback to handle the result after reading the file.


4. In Node.js, what happens if an error occurs in a callback function?

a) The error is ignored.
b) The program stops immediately.
c) The error is passed to the callback as an argument.
d) The callback function is called again.

Answer: c) The error is passed to the callback as an argument.

Explanation: In Node.js, errors that occur in asynchronous operations are passed to the callback as the first argument.


5. Which of the following is a common pattern used to handle errors in Node.js callbacks?

a) try/catch
b) Using process.exit()
c) Checking the first argument in the callback
d) Ignoring the error

Answer: c) Checking the first argument in the callback

Explanation: In Node.js callbacks, the first argument is typically used to handle errors. If there’s no error, it will be null, otherwise it will contain the error.


6. What will happen if a callback function is not provided in Node.js?

a) The program will not work.
b) The asynchronous task will be skipped.
c) Node.js will throw an error.
d) The task will be executed synchronously.

Answer: a) The program will not work.

Explanation: In many Node.js functions, especially those related to I/O operations, a callback is required to handle the asynchronous result. If a callback is missing, it could lead to unexpected behavior.


7. What is a callback hell in Node.js?

a) A way to handle multiple asynchronous tasks without nesting.
b) Nested callback functions leading to unreadable code.
c) A library for managing callbacks.
d) A function that executes tasks synchronously.

Answer: b) Nested callback functions leading to unreadable code.

Explanation: Callback hell refers to the situation where multiple callbacks are nested inside each other, making the code hard to read and maintain.


8. Which of the following is the correct syntax to use a callback in the fs.readFile() method?

a) fs.readFile('file.txt', callback)
b) fs.readFile(callback, 'file.txt')
c) fs.readFile('file.txt', 'utf8', callback)
d) fs.readFile('utf8', 'file.txt', callback)

Answer: c) fs.readFile('file.txt', 'utf8', callback)

Explanation: The fs.readFile() method expects the file path, encoding type, and a callback as arguments.


9. How do you avoid callback hell in Node.js?

a) By using recursion.
b) By using promises or async/await.
c) By using synchronous methods.
d) By ignoring callbacks.

Answer: b) By using promises or async/await.

Explanation: Promises or async/await can help avoid callback hell by allowing more readable, linear code for asynchronous operations.


10. What does the callback function handle in the fs.readFile() method?

a) The file path.
b) The file encoding.
c) The error and data from the file.
d) The number of bytes read.

Answer: c) The error and data from the file.

Explanation: The callback function in fs.readFile() receives two parameters: an error (if one occurs) and the data read from the file.


11. What is the main advantage of using callbacks in Node.js?

a) They provide synchronous behavior.
b) They allow asynchronous, non-blocking operations.
c) They make code more complex.
d) They simplify debugging.

Answer: b) They allow asynchronous, non-blocking operations.

Explanation: Callbacks allow asynchronous execution of tasks, so the event loop does not block, enabling other tasks to be processed concurrently.


12. How do you define a simple callback function in Node.js?

a) function callback() { return result; }
b) function callback(err, data) { if(err) throw err; console.log(data); }
c) callback => { return result; }
d) function callback(err) { return err; }

Answer: b) function callback(err, data) { if(err) throw err; console.log(data); }

Explanation: The correct structure of a callback function includes error handling, typically with two parameters: err and data.


13. What is the purpose of the first argument (err) in a callback function?

a) It stores the data returned from the operation.
b) It stores the result of the operation.
c) It stores the error that occurred, if any.
d) It stores the file path.

Answer: c) It stores the error that occurred, if any.

Explanation: In Node.js, the first argument of the callback is used to handle errors. If no error occurs, it is usually null.


14. Which method in Node.js executes a callback after a delay?

a) setTimeout()
b) setInterval()
c) process.nextTick()
d) fs.writeFile()

Answer: a) setTimeout()

Explanation: setTimeout() executes a callback after a specified delay, allowing asynchronous behavior.


15. How can you make asynchronous code easier to manage in Node.js?

a) By using synchronous methods only.
b) By nesting callbacks.
c) By using promises or async/await.
d) By writing longer callback functions.

Answer: c) By using promises or async/await.

Explanation: Promises and async/await help in managing asynchronous operations more effectively, making the code more readable and reducing callback hell.


16. Which of the following methods do not require a callback in Node.js?

a) fs.readFile()
b) setTimeout()
c) fs.existsSync()
d) http.createServer()

Answer: c) fs.existsSync()

Explanation: fs.existsSync() is a synchronous method, so it does not require a callback.


17. What does fs.writeFile() do in Node.js?

a) It reads a file asynchronously.
b) It writes to a file asynchronously.
c) It writes to a file synchronously.
d) It creates a new file.

Answer: b) It writes to a file asynchronously.

Explanation: fs.writeFile() is used to write data to a file asynchronously and takes a callback function to handle success or error.


18. Which of the following is a disadvantage of using callbacks?

a) The code becomes more readable.
b) Callbacks make asynchronous operations easier.
c) Callbacks can lead to callback hell with complex nesting.
d) Callbacks are easy to debug.

Answer: c) Callbacks can lead to callback hell with complex nesting.

Explanation: Callback hell happens when multiple callbacks are nested inside one another, making the code difficult to read and maintain.


19. What is the process.nextTick() function in Node.js used for?

a) It handles asynchronous operations.
b) It schedules a callback to be invoked on the next iteration of the event loop.
c) It handles errors in callbacks.
d) It schedules a callback after a delay.

Answer: b) It schedules a callback to be invoked on the next iteration of the event loop.

Explanation: process.nextTick() allows you to schedule a callback to be invoked before any I/O events or timers.


20. What happens if the callback in fs.readFile() is not provided?

a) The file will be read synchronously.
b) An error will be thrown.
c) The operation will continue without issues.
d) The file data will be logged automatically.

Answer: b) An error will be thrown.

Explanation: If the callback is missing in an asynchronous operation like fs.readFile(), Node.js will throw an error because it doesn’t know what to do with the result.


(Continuing with additional questions...)

Let me know if you'd like to continue or need more specific focus on certain aspects!

4o mini

You said:

yes

ChatGPT said:

ChatGPT

Here are the next set of MCQs, continuing from the previous questions:


21. What is the purpose of callbacks in Node.js?

a) To handle asynchronous tasks without blocking the event loop.
b) To handle synchronous tasks.
c) To handle network requests.
d) To handle file read/write operations only.

Answer: a) To handle asynchronous tasks without blocking the event loop.

Explanation: Callbacks are used to handle asynchronous tasks in Node.js, enabling non-blocking operations and allowing the event loop to continue processing other tasks.


22. What does the callback function in a setTimeout() method do?

a) It is invoked after a specified delay.
b) It is invoked immediately after the function is called.
c) It handles errors in the operation.
d) It processes multiple timers at once.

Answer: a) It is invoked after a specified delay.

Explanation: The callback function in setTimeout() is invoked after the specified delay period, allowing asynchronous code execution.


23. Which of the following Node.js methods is synchronous and blocks the event loop?

a) fs.readFile()
b) fs.writeFile()
c) fs.existsSync()
d) setTimeout()

Answer: c) fs.existsSync()

Explanation: fs.existsSync() is a synchronous method and blocks the event loop while it performs the task.


24. How can you handle multiple asynchronous operations in Node.js?

a) By using nested callbacks (callback hell).
b) By using setTimeout().
c) By using Promises or async/await.
d) By using synchronous methods only.

Answer: c) By using Promises or async/await.

Explanation: Promises or async/await help handle multiple asynchronous operations more effectively by reducing the complexity of nested callbacks.


25. Which of the following statements is true about the callback function in asynchronous operations?

a) It is always executed synchronously.
b) It can accept multiple arguments.
c) It can only handle one task at a time.
d) It doesn’t need to be passed as a parameter.

Answer: b) It can accept multiple arguments.

Explanation: Callback functions can accept multiple arguments, including the error (if any) and the data returned from the asynchronous operation.


26. What will be the output if you try to log a callback function in Node.js?

a) It will execute immediately.
b) It will print an error message.
c) It will print the definition of the callback function.
d) It will print undefined.

Answer: c) It will print the definition of the callback function.

Explanation: If you log a callback function, Node.js will print its definition (like a reference to the function), not its execution result.


27. How do you handle errors in callbacks in Node.js?

a) By using a try/catch block inside the callback.
b) By checking the first argument in the callback.
c) By catching errors in promises.
d) By ignoring the errors.

Answer: b) By checking the first argument in the callback.

Explanation: In Node.js, errors are passed as the first argument to the callback. You should check this argument to determine if an error occurred.


28. What does the following callback pattern in Node.js represent?

javascript

CopyEdit

function callback(err, data) {

  if (err) {

    console.error(err);

    return;

  }

  console.log(data);

}

a) The callback handles a synchronous task.
b) The callback handles asynchronous file operations.
c) The callback is used to handle errors only.
d) The callback is executed immediately.

Answer: b) The callback handles asynchronous file operations.

Explanation: The pattern handles an asynchronous task like file operations, where err represents any errors and data represents the operation result.


29. How would you handle multiple asynchronous tasks sequentially in Node.js?

a) By nesting callbacks.
b) By using async/await or Promises.
c) By using synchronous methods.
d) By using setInterval().

Answer: b) By using async/await or Promises.

Explanation: Using async/await or Promises allows you to manage multiple asynchronous tasks in a sequential and readable manner, avoiding callback hell.


30. What happens if an error occurs inside a callback function in Node.js?

a) The program crashes immediately.
b) The callback function is re-executed.
c) The error is passed to the callback as the first argument.
d) The callback will not be called.

Answer: c) The error is passed to the callback as the first argument.

Explanation: In Node.js, errors occurring in asynchronous operations are passed to the callback as the first argument, allowing you to handle them.


31. In Node.js, how can you prevent blocking the event loop when handling I/O tasks?

a) By using synchronous file operations.
b) By using asynchronous methods with callbacks.
c) By using the setTimeout() method.
d) By using promises.

Answer: b) By using asynchronous methods with callbacks.

Explanation: Asynchronous methods like fs.readFile() allow I/O tasks to be handled without blocking the event loop, making the application more efficient.


32. Which method in Node.js is used to read a file asynchronously?

a) fs.readFileSync()
b) fs.open()
c) fs.readFile()
d) fs.writeFileSync()

Answer: c) fs.readFile()

Explanation: fs.readFile() is an asynchronous method used to read files without blocking the event loop.


33. What is the purpose of setImmediate() in Node.js?

a) It schedules a callback to run immediately after the current operation completes.
b) It executes a callback after a specific delay.
c) It schedules the callback to run before I/O tasks.
d) It executes a callback synchronously.

Answer: a) It schedules a callback to run immediately after the current operation completes.

Explanation: setImmediate() schedules a callback to run during the next iteration of the event loop, right after the current operation completes.


34. Which of the following is a potential drawback of using callbacks?

a) They make the code more readable.
b) They can cause callback hell with multiple levels of nesting.
c) They can make asynchronous code synchronous.
d) They provide a simple way to handle I/O tasks.

Answer: b) They can cause callback hell with multiple levels of nesting.

Explanation: Callback hell occurs when multiple asynchronous operations are nested, making the code hard to read and maintain.


35. What will happen if you omit the callback function in the fs.readFile() method?

a) An error will be thrown.
b) The file content will be logged automatically.
c) The file will be read synchronously.
d) The operation will be ignored.

Answer: a) An error will be thrown.

Explanation: If the callback is missing, the fs.readFile() method will throw an error because it doesn’t know what to do with the result.


36. How does Node.js execute asynchronous functions without blocking the event loop?

a) By using synchronous operations.
b) By using event-driven callbacks.
c) By using Promises only.
d) By using recursive functions.

Answer: b) By using event-driven callbacks.

Explanation: Node.js uses event-driven, non-blocking callbacks to handle I/O operations asynchronously, ensuring that the event loop remains unblocked.


37. Which of the following is an advantage of using async/await over callbacks?

a) It makes the code easier to read and write.
b) It is always faster than using callbacks.
c) It automatically handles errors without any try/catch.
d) It runs synchronous code asynchronously.

Answer: a) It makes the code easier to read and write.

Explanation: async/await provides a more readable and cleaner way to handle asynchronous operations as opposed to using nested callbacks.


38. What type of function does fs.readFile() expect as its second argument?

a) A promise function.
b) A callback function.
c) A synchronous function.
d) A function that handles errors only.

Answer: b) A callback function.

Explanation: fs.readFile() expects a callback function as its second argument, which is executed when the file reading operation is completed.


39. Which method can be used to execute a function after all I/O events are completed in Node.js?

a) setTimeout()
b) setInterval()
c) process.nextTick()
d) setImmediate()

Answer: d) setImmediate()

Explanation: setImmediate() is used to execute a function after the current event loop iteration and all I/O events are completed.


40. How can you handle multiple asynchronous operations concurrently in Node.js?

a) By nesting callbacks.
b) By using Promise.all()
c) By using setTimeout()
d) By using async/await inside callbacks.

Answer: b) By using Promise.all()

Explanation: Promise.all() allows you to execute multiple asynchronous tasks concurrently and wait for all of them to complete.


(Continuing to build the set of 100 MCQs...)

Would you like to continue further or need additional support on specific sections?

4o mini

You said:

yes

ChatGPT said:

ChatGPT

Here are the next set of MCQs continuing from the previous ones:


41. Which of the following is NOT a core module of Node.js?

a) http
b) fs
c) os
d) jQuery

Answer: d) jQuery

Explanation: jQuery is a JavaScript library, not a core module in Node.js. The core modules include http, fs, and os.


42. Which function is used to read files synchronously in Node.js?

a) fs.readFile()
b) fs.readFileSync()
c) fs.open()
d) fs.writeFile()

Answer: b) fs.readFileSync()

Explanation: fs.readFileSync() is used to read files synchronously, meaning it blocks the event loop until the file is completely read.


43. What happens if a callback in Node.js contains an error argument and is not handled?

a) The program will crash immediately.
b) The error will be logged automatically.
c) The callback will be ignored.
d) The error will be passed to the next callback.

Answer: a) The program will crash immediately.

Explanation: If an error is passed in the callback and not handled, it may cause the application to crash or behave unexpectedly.


44. In which case would you prefer to use a callback function over async/await?

a) When working with synchronous code.
b) When managing file read/write operations in Node.js.
c) When managing simple promises.
d) When handling long-running, CPU-heavy operations.

Answer: b) When managing file read/write operations in Node.js.

Explanation: Callbacks are commonly used for file operations in Node.js, particularly for I/O-bound tasks, where async/await can also be an option for better readability.


45. Which of the following is the default method for handling errors in asynchronous callbacks in Node.js?

a) Throwing an exception.
b) Returning an error object.
c) Passing the error as the first argument in the callback.
d) Using try/catch.

Answer: c) Passing the error as the first argument in the callback.

Explanation: In Node.js, errors are passed as the first argument to a callback function, and it’s standard to check for the error before processing the data.


46. What does the following callback pattern in Node.js represent?

javascript

CopyEdit

fs.readFile('file.txt', 'utf8', function(err, data) {

  if (err) throw err;

  console.log(data);

});

a) Reading the file synchronously.
b) An asynchronous file reading operation with error handling.
c) A synchronous operation with callback function.
d) Handling multiple asynchronous operations.

Answer: b) An asynchronous file reading operation with error handling.

Explanation: This is an example of using the fs.readFile() function to read a file asynchronously, where errors are handled by checking the err argument.


47. What is the main benefit of asynchronous programming in Node.js?

a) It allows multiple threads to be used concurrently.
b) It makes the program faster and non-blocking.
c) It improves the handling of CPU-intensive operations.
d) It helps in writing synchronous code in a non-blocking way.

Answer: b) It makes the program faster and non-blocking.

Explanation: Asynchronous programming in Node.js ensures non-blocking operations, meaning tasks can run concurrently without stopping the event loop, improving the program's performance.


48. Which of the following methods would you use to handle multiple asynchronous tasks and return their results in Node.js?

a) setImmediate()
b) fs.readFile()
c) Promise.all()
d) callback()

Answer: c) Promise.all()

Explanation: Promise.all() allows you to execute multiple asynchronous tasks concurrently and return their results as a single promise when all tasks are complete.


49. Which Node.js module is used for file system operations like reading and writing files?

a) http
b) fs
c) url
d) process

Answer: b) fs

Explanation: The fs module in Node.js provides functions to interact with the file system, such as reading and writing files.


50. Which of the following statements correctly defines asynchronous operations in Node.js?

a) Asynchronous operations run synchronously with the main thread.
b) Asynchronous operations do not block the event loop and allow other operations to execute.
c) Asynchronous operations are only useful for synchronous I/O.
d) Asynchronous operations require multiple threads for execution.

Answer: b) Asynchronous operations do not block the event loop and allow other operations to execute.

Explanation: Asynchronous operations allow Node.js to perform non-blocking I/O tasks, which makes it highly efficient for I/O-heavy applications.


51. What is the event loop in Node.js responsible for?

a) Managing memory usage.
b) Executing JavaScript code sequentially.
c) Handling multiple asynchronous operations.
d) Running JavaScript in parallel threads.

Answer: c) Handling multiple asynchronous operations.

Explanation: The event loop in Node.js manages and processes asynchronous operations, ensuring non-blocking execution in a single-threaded environment.


52. Which of the following can cause callback hell in Node.js?

a) Using synchronous methods.
b) Using nested callbacks for multiple asynchronous operations.
c) Using Promises.
d) Using setImmediate().

Answer: b) Using nested callbacks for multiple asynchronous operations.

Explanation: Callback hell occurs when there are too many nested callbacks, making the code difficult to read and maintain.


53. Which statement is true about the setTimeout() function in Node.js?

a) It executes a callback immediately.
b) It schedules a callback to execute after a delay.
c) It runs the callback at regular intervals.
d) It is used for synchronous operations.

Answer: b) It schedules a callback to execute after a delay.

Explanation: setTimeout() schedules a callback to execute after a specified delay, enabling delayed asynchronous behavior.


54. How can you improve code readability and avoid callback hell in Node.js?

a) By using synchronous methods.
b) By using Promises or async/await.
c) By avoiding callbacks altogether.
d) By using setTimeout().

Answer: b) By using Promises or async/await.

Explanation: async/await and Promises simplify the handling of asynchronous tasks, making code more readable and avoiding deeply nested callbacks.


55. What does the fs.writeFile() method do in Node.js?

a) It writes data to a file synchronously.
b) It creates a new file if it does not exist.
c) It reads the contents of a file.
d) It deletes a file.

Answer: b) It creates a new file if it does not exist.

Explanation: fs.writeFile() writes data to a file, creating the file if it does not exist, and replaces the content if the file already exists.


56. Which method is used to parse URL strings in Node.js?

a) url.parse()
b) url.format()
c) url.resolve()
d) url.connect()

Answer: a) url.parse()

Explanation: url.parse() is used to parse URL strings into an object in Node.js, allowing easy access to individual components like the hostname, path, etc.


57. What does process.nextTick() do in Node.js?

a) It schedules a callback to run immediately after the current operation completes.
b) It schedules a callback to run after a set delay.
c) It starts the event loop.
d) It executes the callback before I/O events.

Answer: a) It schedules a callback to run immediately after the current operation completes.

Explanation: process.nextTick() ensures that the callback function is executed after the current operation, but before the event loop proceeds to I/O events.


58. What is the significance of passing the error as the first argument in a Node.js callback function?

a) It is a convention used to simplify error handling.
b) It ensures that errors are handled after the data is processed.
c) It automatically logs errors to the console.
d) It helps return data to the calling function.

Answer: a) It is a convention used to simplify error handling.

Explanation: Passing the error as the first argument allows easy checking and handling of errors in asynchronous operations, simplifying error management.


59. Which method is used to create a simple HTTP server in Node.js?

a) http.createServer()
b) http.request()
c) http.listen()
d) http.makeServer()

Answer: a) http.createServer()

Explanation: The http.createServer() method is used to create a new HTTP server in Node.js, which can handle requests and send responses.


60. Which of the following can be done using the http module in Node.js?

a) Make HTTP requests
b) Create a server to handle HTTP requests
c) Handle file system operations
d) Perform DNS lookups

Answer: b) Create a server to handle HTTP requests

Explanation: The http module in Node.js is primarily used to create HTTP servers and handle HTTP requests and responses.


Let me know if you'd like me to continue or need any adjustments!

4o mini

You said:

yes

ChatGPT said:

ChatGPT

Here are additional MCQs continuing from the previous set:


61. Which HTTP method is commonly used to submit form data in Node.js?

a) GET
b) POST
c) PUT
d) DELETE

Answer: b) POST

Explanation: The POST method is typically used to submit form data to the server for processing, especially when the data is sent in the body of the request.


62. What does fs.appendFile() do in Node.js?

a) Writes data to a file asynchronously, replacing the content.
b) Reads the file contents asynchronously.
c) Appends data to a file asynchronously.
d) Creates a new file.

Answer: c) Appends data to a file asynchronously.

Explanation: fs.appendFile() appends data to the specified file, if the file exists. If the file does not exist, it creates the file.


63. What is the purpose of the http module in Node.js?

a) To handle file system operations.
b) To make HTTP requests.
c) To create an HTTP server and handle requests.
d) To manage databases.

Answer: c) To create an HTTP server and handle requests.

Explanation: The http module in Node.js is used to create an HTTP server, handle client requests, and send responses.


64. Which of the following statements about the path module in Node.js is true?

a) It is used for handling HTTP requests.
b) It provides utilities for working with URLs.
c) It provides utilities for manipulating file paths.
d) It is used to manipulate arrays.

Answer: c) It provides utilities for manipulating file paths.

Explanation: The path module in Node.js provides utilities to work with file and directory paths, like joining paths, resolving them, and getting the file extension.


65. How does Node.js handle multiple asynchronous operations?

a) Through multi-threading.
b) By using the event loop and callbacks.
c) By queuing synchronous operations.
d) By using the async keyword.

Answer: b) By using the event loop and callbacks.

Explanation: Node.js uses the event loop to handle multiple asynchronous operations non-blocking. It allows callbacks to be executed after operations complete, without blocking the event loop.


66. Which method is used to handle URL query strings in Node.js?

a) url.parse()
b) url.format()
c) url.query()
d) url.resolve()

Answer: a) url.parse()

Explanation: The url.parse() method parses a URL string into its components and provides an object containing properties like hostname, pathname, and query.


67. What is the output of this code?

javascript

CopyEdit

const fs = require('fs');

 

fs.readFile('example.txt', 'utf8', (err, data) => {

  if (err) throw err;

  console.log(data);

});

a) The contents of example.txt.
b) An error message.
c) An empty string.
d) A synchronous read of the file.

Answer: a) The contents of example.txt.

Explanation: This code reads the file example.txt asynchronously. If no error occurs, the contents of the file are logged to the console.


68. Which of the following statements about asynchronous programming in Node.js is true?

a) It blocks the main thread until all tasks are completed.
b) It allows I/O operations to execute without blocking the event loop.
c) It requires multiple threads to execute code concurrently.
d) It always requires the use of Promises.

Answer: b) It allows I/O operations to execute without blocking the event loop.

Explanation: Asynchronous programming in Node.js enables non-blocking execution, so I/O operations can run while other code is executing, increasing performance.


69. Which of the following is the default character encoding when reading a file using fs.readFile()?

a) utf8
b) ascii
c) base64
d) binary

Answer: a) utf8

Explanation: The default character encoding when reading a file using fs.readFile() is utf8, which ensures the file contents are returned as a string.


70. How can you send a custom status code with a response in Node.js HTTP server?

a) res.statusCode(200)
b) res.setStatus(200)
c) res.writeStatus(200)
d) res.status(200)

Answer: a) res.statusCode(200)

Explanation: res.statusCode = 200; is used to set the status code of the response in a Node.js HTTP server.


71. Which module in Node.js helps in handling incoming HTTP requests?

a) os
b) path
c) http
d) dns

Answer: c) http

Explanation: The http module is responsible for creating an HTTP server and handling incoming requests, which makes it an essential module for building web servers.


72. What is the role of the callback function in asynchronous methods like fs.readFile()?

a) It executes synchronously with the main thread.
b) It handles errors and processes data once the asynchronous operation completes.
c) It stops the program from running.
d) It forces the program to wait for the operation to finish.

Answer: b) It handles errors and processes data once the asynchronous operation completes.

Explanation: The callback function is called after the asynchronous operation completes, allowing you to handle any errors or process the data returned from the operation.


73. Which of the following is used to handle different HTTP request methods (GET, POST, etc.) in Node.js?

a) http.createServer()
b) http.request()
c) http.listen()
d) http.handleRequest()

Answer: a) http.createServer()

Explanation: The http.createServer() method is used to create a new server that listens for different HTTP request methods and provides the ability to handle them in the callback function.


74. How can you send data in the body of a POST request using Node.js HTTP server?

a) Using the query object.
b) Using the req.body object.
c) Using the req.headers.
d) Using the res.write() method.

Answer: b) Using the req.body object.

Explanation: The req.body object is used to access the data sent in the body of a POST request, but you need middleware like express.json() to parse it.


75. How can you concatenate two file paths in Node.js?

a) path.concatenate()
b) path.concat()
c) path.join()
d) path.add()

Answer: c) path.join()

Explanation: path.join() is used to concatenate multiple file paths into one, ensuring the correct handling of file separators across different operating systems.


76. How can you retrieve the file extension of a file in Node.js?

a) path.getExtension()
b) path.extension()
c) path.extname()
d) path.fileExtension()

Answer: c) path.extname()

Explanation: path.extname() returns the file extension of the specified file path.


77. Which of the following methods is used to send data back to the client in a Node.js HTTP server?

a) response.send()
b) response.write()
c) response.writeHead()
d) response.end()

Answer: b) response.write()

Explanation: response.write() is used to send data back to the client in the HTTP response. It can be used multiple times before calling response.end().


78. What is the main purpose of the os module in Node.js?

a) To handle HTTP requests.
b) To interact with the file system.
c) To manage system-level operations like CPU, memory, and user information.
d) To parse URLs.

Answer: c) To manage system-level operations like CPU, memory, and user information.

Explanation: The os module in Node.js provides operating system-related utility functions, such as retrieving system information, memory, and network interfaces.


79. Which of the following methods would you use to delete a file in Node.js?

a) fs.remove()
b) fs.unlink()
c) fs.delete()
d) fs.removeFile()

Answer: b) fs.unlink()

Explanation: fs.unlink() is used to delete a file in Node.js.


80. Which method is used to handle HTTP POST requests in Node.js?

a) http.get()
b) http.request()
c) http.post()
d) http.createServer()

Answer: b) http.request()

Explanation: The http.request() method can be used to handle HTTP POST requests by specifying the method as POST and sending the necessary data.


Let me know if you'd like to continue!

4o mini

You said:

yes

ChatGPT said:

ChatGPT

Here are more MCQs continuing from the previous set:


81. In Node.js, which of the following modules is used to parse URLs?

a) url
b) path
c) http
d) fs

Answer: a) url

Explanation: The url module is used to parse URLs and extract their components like hostname, pathname, and query.


82. Which of the following statements about the req and res objects in an HTTP server is true?

a) req is used to send data to the client, and res is used to receive data from the client.
b) req is used to receive data from the client, and res is used to send data to the client.
c) Both req and res are used to send data to the client.
d) req and res are both used to handle the file system.

Answer: b) req is used to receive data from the client, and res is used to send data to the client.

Explanation: In an HTTP request-response cycle, req (request) contains data sent from the client, while res (response) is used to send data back to the client.


83. Which of the following is the correct way to start a Node.js HTTP server?

a) http.start()
b) http.begin()
c) http.listen()
d) http.createServer()

Answer: c) http.listen()

Explanation: The listen() method is used to bind and listen for connections on the specified host and port in an HTTP server.


84. In Node.js, which method is used to read a file asynchronously?

a) fs.readFileSync()
b) fs.read()
c) fs.readFile()
d) fs.fileRead()

Answer: c) fs.readFile()

Explanation: fs.readFile() is the asynchronous version of reading files, where a callback function is used to handle the file data once it is read.


85. What does the fs.writeFile() method do in Node.js?

a) Reads the contents of a file asynchronously.
b) Appends data to a file.
c) Writes data to a file asynchronously, replacing the file's contents.
d) Deletes a file.

Answer: c) Writes data to a file asynchronously, replacing the file's contents.

Explanation: fs.writeFile() writes data to a file asynchronously and replaces any existing content in the file.


86. Which method is used to retrieve the query string from a URL in Node.js?

a) url.query()
b) url.parse()
c) url.get()
d) url.parse().query()

Answer: d) url.parse().query()

Explanation: url.parse() parses a URL into components, and .query extracts the query string from the URL.


87. What does the http.createServer() method in Node.js do?

a) It handles incoming HTTP requests.
b) It starts an HTTP server that listens for incoming requests.
c) It handles the client's requests and sends responses.
d) All of the above.

Answer: d) All of the above.

Explanation: http.createServer() is used to create an HTTP server that listens for requests and processes them based on the logic defined in the callback function.


88. In Node.js, which module is used to work with file paths?

a) url
b) os
c) path
d) http

Answer: c) path

Explanation: The path module provides utilities for working with file and directory paths, such as joining paths and extracting extensions.


89. What happens if a file is not found when using fs.readFile() in Node.js?

a) The program throws an error and stops execution.
b) The file is created automatically.
c) The callback function's error argument is populated.
d) A warning is logged to the console, but the program continues.

Answer: c) The callback function's error argument is populated.

Explanation: If the file is not found, an error is passed to the callback function. You can then handle it appropriately, such as logging the error or performing other actions.


90. Which of the following is true about asynchronous programming in Node.js?

a) Asynchronous code runs in parallel with the main thread, blocking it.
b) Asynchronous code is executed in the main thread in Node.js.
c) Asynchronous code is executed in parallel with non-blocking I/O.
d) Asynchronous code can only be executed using Promises.

Answer: c) Asynchronous code is executed in parallel with non-blocking I/O.

Explanation: In Node.js, asynchronous operations do not block the event loop. Instead, they execute non-blocking I/O operations, allowing the event loop to continue handling other tasks.


91. How can you parse the contents of a POST request in Node.js without using external libraries?

a) Using JSON.parse()
b) Using req.on('data') and req.on('end')
c) Using req.body.parse()
d) Using JSON.stringify()

Answer: b) Using req.on('data') and req.on('end')

Explanation: Node.js allows you to manually parse incoming request data by listening to the data event (for chunks of data) and the end event (when the full request body is received).


92. What does the res.end() method do in Node.js?

a) Ends the response and sends data back to the client.
b) Ends the server connection.
c) Closes the database connection.
d) Ends the script execution.

Answer: a) Ends the response and sends data back to the client.

Explanation: res.end() is used to signal that the response is complete and that no further data will be written to the response.


93. Which HTTP status code indicates a successful request in Node.js?

a) 404
b) 500
c) 200
d) 302

Answer: c) 200

Explanation: HTTP status code 200 indicates that the request has been successfully processed and that the response contains the requested data.


94. Which of the following would you use to handle a GET request in a Node.js HTTP server?

a) req.get()
b) http.get()
c) res.get()
d) req.method === 'GET'

Answer: d) req.method === 'GET'

Explanation: To check if an incoming request is a GET request, you can evaluate req.method and compare it with 'GET'.


95. How can you send JSON data as a response in Node.js?

a) res.write(JSON.stringify(data))
b) res.send(data)
c) res.json(data)
d) res.writeJSON(data)

Answer: c) res.json(data)

Explanation: res.json() is used to send JSON data as a response in Node.js. This automatically sets the correct Content-Type header.


96. What is the default port used by HTTP servers in Node.js?

a) 3000
b) 8080
c) 5000
d) 80

Answer: a) 3000

Explanation: While the default HTTP port is 80, in development, it's common to use port 3000 for Node.js servers.


97. What does the path.basename() method in Node.js return?

a) The full file path.
b) The directory name.
c) The file name with extension.
d) The file extension.

Answer: c) The file name with extension.

Explanation: path.basename() returns the last portion of a path, which is typically the file name, including its extension.


98. How do you handle errors in an HTTP request callback in Node.js?

a) By using try-catch blocks.
b) By using error event listeners.
c) By checking the err parameter in the callback.
d) By throwing an error.

Answer: c) By checking the err parameter in the callback.

Explanation: Errors in asynchronous methods like fs.readFile() are handled using the err parameter in the callback function, allowing you to respond appropriately.


99. Which of the following is true about the http module's createServer() method in Node.js?

a) It is used to create a request handler.
b) It listens for requests and returns a response.
c) It is used to generate the request URL.
d) It only handles GET requests.

Answer: b) It listens for requests and returns a response.

Explanation: http.createServer() creates a server that listens for requests and sends responses based on the logic in the callback.


100. How can you check if a file exists in Node.js?

a) fs.existsSync()
b) fs.check()
c) fs.isExist()
d) fs.fileExists()

Answer: a) fs.existsSync()

Explanation: fs.existsSync() checks if a file or directory exists synchronously.


 

No comments:

Post a Comment

Search This Blog

Powered by Blogger.