CRT-600 practice question 28 of 30

developer creates a new web server that uses Node.js. It imports a server library that uses events and callbacks for handling server functionality…

Full set: 223 questions
developer creates a new web server that uses Node.js. It imports a server library that uses events and callbacks for handling server functionality. The server library is imported with require and is made available to the code by a variable named server. The developer wants to log any issues that the server has while booting up. Given the code and the information the developer has, which code logs an error at boost with an event?
Answer options
A: Server.catch ((server) => { console.log(‘ERROR’, error); });
B: Server.error ((server) => { console.log(‘ERROR’, error); });
C: Server.on (‘error’, (error) => { console.log(‘ERROR’, error); }); Correct answer
D: Try{ server.start(); } catch(error) { console.log(‘ERROR’, error); }
Correct Answer:
C. Server.on (‘error’, (error) => { console.log(‘ERROR’, error); });
Explanation

The question describes a server library that uses "events and callbacks," which is the core of Node.js's asynchronous, event-driven architecture. The standard mechanism for handling such events is the EventEmitter class. The .on(eventName, listener) method is the idiomatic way to register a listener (a callback function) for a specific event. The 'error' event is a special, conventional event that is emitted when an error occurs. Therefore, server.on('error', callback) is the correct syntax to listen for and handle errors emitted by the server object.

Why Incorrect

A. Server.catch(...) is the syntax for handling rejected Promises, not for listening to events from an EventEmitter.
B. Server.error(...) is not a standard method for registering an event listener in the Node.js events module or common server libraries.
D. try...catch is a construct for handling synchronous exceptions. It cannot catch asynchronous errors that are emitted as events after the initial synchronous code block has completed.

References

1. Node.js v20.x Documentation

Events Module: The official documentation specifies the use of emitter.on(eventName

listener) to register event listeners. It also highlights the special nature of 'error' events.

Section: emitter.on(eventName

listener)

Section: Error events: "When an error occurs within an EventEmitter instance

the typical action is for an 'error' event to be emitted."

2. Node.js v20.x Documentation

Class: EventEmitter: This section details the foundational class for event-driven programming in Node.js.

Section: Class: EventEmitter

3. Full Stack Development with Node.js

Module: Node.js Modules and File System

Content: "The core of the Node.js is the event-driven architecture. Many objects in Node raise events... We can subscribe to these events by using the on() method."

Scroll to Top