Node.js API Comprehensive Quiz & Projects
30 questions on Node.js APIs Tutorial.
Question 1: How does the Node.js Event Loop handle asynchronous I/O operations without multi-threading?
- A. By delegating all execution to the OS kernel or utilizing a pool of background worker threads via libuv. β (correct answer)
- B. By pausing main thread execution until the network response arrives.
- C. By generating dynamic subprocesses for every event registration.
- D. By running JavaScript code in parallel across all available CPU cores.
Explanation: Node.js is single-threaded but achieves high concurrency by delegating blocking operations to the system kernel or libuv's thread pool.
Question 2: When reading a 10GB log file in Node.js, why is using Streams preferred over fs.readFile?
- A. Streams automatically encrypt file data to prevent memory leakage.
- B. fs.readFile loads the entire file into buffer memory, risking heap out-of-memory errors, whereas Streams process data in small chunks. β (correct answer)
- C. Streams execute synchronous queries, which are faster.
- D. fs.readFile deletes the file after reading, while Streams preserve it.
Explanation: Streams process data chunk-by-chunk in a memory-efficient manner without overloading the RAM.
Question 3: What is the purpose of Node.js Cluster module?
- A. To group multiple databases together to handle concurrent read operations.
- B. To load balance incoming HTTP requests across multiple independent web servers globally.
- C. To spawn a cluster of child processes that share server ports, allowing single-threaded Node to utilize multi-core CPUs. β (correct answer)
- D. To pool database connections and cache them in memory.
Explanation: The cluster module allows easy creation of child processes that share server ports, enabling scaling across all CPU cores.
Question 4: What is the primary difference in execution between CommonJS require() and ES Module import?
- A. require() is asynchronous and resolved at runtime, while import is synchronous.
- B. require() loads modules synchronously and evaluates them at runtime, whereas import is static and resolved at compile time. β (correct answer)
- C. require() is deprecated in Node.js 18+ and will throw exceptions if used.
- D. require() loads packages directly from the web, while import loads them locally.
Explanation: CommonJS modules are loaded synchronously and evaluated dynamically. ES Modules are statically analyzed before execution.
Question 5: How should you capture unhandled promise rejections in Node.js to prevent abrupt process termination?
- A. By wrapping the entire application entry point in a try-catch block.
- B. By listening to the 'unhandledRejection' event on the global process object. β (correct answer)
- C. By configuring the server firewall to block invalid promises.
- D. By disabling async/await syntax and using raw callbacks instead.
Explanation: Listening to process.on('unhandledRejection', callback) allows logging and clean teardown of unhandled async rejections.
Question 6: Which core module handles file path operations like combining segments safely across operating systems?
- A. fs
- B. path β (correct answer)
- C. url
- D. os
Explanation: The path module provides utilities like path.join() to resolve folder segments using OS-specific delimiters.
Question 7: What is a Node.js Buffer?
- A. A database query caching engine.
- B. A temporary memory space used to store raw binary data outside the V8 engine heap. β (correct answer)
- C. A system firewall configuration tool.
- D. A class used to bundle static asset files.
Explanation: Buffers represent fixed-length memory blocks, crucial for handling stream binary data.
Question 8: What is the purpose of libuv in the Node.js architecture?
- A. It compiles JavaScript code into machine binary.
- B. It is a multi-platform support library that provides thread pooling, event looping, and asynchronous I/O capabilities. β (correct answer)
- C. It handles TLS encryption for HTTPS traffic.
- D. It parses JSON payloads in network calls.
Explanation: libuv handles background tasks (file I/O, network sockets) asynchronously using OS APIs or a thread pool.
Question 9: Which global object contains metadata about the active Node.js execution runtime, including environment variables?
- A. window
- B. process β (correct answer)
- C. console
- D. module
Explanation: The process object holds process.env, process.argv, and system exit signals.
Question 10: In Node.js, what does the Event Emitter class do?
- A. It compiles SCSS files to CSS.
- B. It implements the Observer pattern, allowing objects to emit named events and register listeners. β (correct answer)
- C. It handles cluster process routing.
- D. It acts as a database connection pool.
Explanation: Any object that emits events is an instance of the EventEmitter class, binding callback functions to keywords.
Question 11: What is the difference between process.nextTick() and setImmediate()?
- A. process.nextTick() executes immediately after the current operation finishes, before the event loop continues. setImmediate() executes on the next event loop iteration phase. β (correct answer)
- B. setImmediate() runs faster and uses less CPU resources.
- C. process.nextTick() is asynchronous, while setImmediate() is synchronous.
- D. setImmediate() bypasses the libuv thread pool.
Explanation: nextTick callbacks are processed immediately after the call stack clears, preempting normal event loop phases.
Question 12: Which module should you use to execute system commands or external binary files in Node.js?
- A. os
- B. child_process β (correct answer)
- C. cluster
- D. readline
Explanation: child_process methods like exec and spawn run system processes, capturing stdin/stdout.
Question 13: Which command-line tool package runner executes packages directly without installing them globally?
- A. npm
- B. npx β (correct answer)
- C. node
- D. yarn
Explanation: npx fetches and runs packages dynamically, keeping the global npm context clean.
Question 14: Why is child_process.spawn() preferred over child_process.exec() for long-running processes that output massive data?
- A. spawn() runs synchronously, which prevents memory leaks.
- B. exec() buffers the entire output in memory, risking buffer overflows, while spawn() returns stream pipes to process data chunk-by-chunk. β (correct answer)
- C. exec() is deprecated in modern Node.js versions.
- D. spawn() automatically runs on multiple servers.
Explanation: spawn uses streams for stdout/stderr, making it ideal for processing heavy or continuous binary outputs.
Question 15: What does Node.js package.json file define?
- A. The environment credentials database keys.
- B. Project metadata, script commands, and dependency version configurations. β (correct answer)
- C. The local firewall access rules.
- D. Client-side html template directories.
Explanation: package.json is the package manifest, declaring library versions and executable commands.
Question 16: What are Worker Threads in Node.js?
- A. Background process logs monitors.
- B. A module that enables executing CPU-intensive JavaScript tasks in parallel threads sharing parent memory, bypassing single-thread blockages. β (correct answer)
- C. Background tasks that run database migrations.
- D. Threads that route traffic between servers.
Explanation: Worker threads allow parallel JS computation without spawning separate full OS process runtimes.
Question 17: How do you write data synchronously to a file using the fs module?
- A. fs.writeFile()
- B. fs.writeFileSync() β (correct answer)
- C. fs.appendFile()
- D. fs.writeSync()
Explanation: Functions ending in 'Sync' block thread execution until the disk operation completes.
Question 18: What does npm shrinkwrap or package-lock.json guarantee?
- A. That dependencies are compressed to reduce bundle size.
- B. That exact, identical dependency versions are installed across different developer machines and server builds. β (correct answer)
- C. That the project is encrypted before publishing.
- D. That all databases are compiled locally.
Explanation: The lock file records precise dependency trees, preventing version mismatch conflicts.
Question 19: What is the purpose of the 'exports' field in a package.json file?
- A. Exporting database schemas to XML format.
- B. Defining explicit entry points for a module, restricting which files can be imported by consuming applications. β (correct answer)
- C. Listing public variables for other system processes.
- D. Declaring global shell command aliases.
Explanation: The exports block controls encapsulation, defining module entry paths for CJS and ESM loaders.
Question 20: What is the role of Node.js stream backpressure?
- A. Encrypting stream packets to prevent sniffing.
- B. A control mechanism where a readable stream pauses reading when the writable stream's buffer buffer limit is exceeded, preventing memory exhaustion. β (correct answer)
- C. Compressing stream variables into base64.
- D. Redirecting requests to backup servers.
Explanation: Backpressure stops the system from overloading RAM when incoming speed exceeds output write speed.
Question 21: Which method is used to import a JSON file in CommonJS?
- A. require('./file.json') β (correct answer)
- B. import('./file.json')
- C. fs.readJSON()
- D. JSON.parse()
Explanation: CommonJS require() parses and resolves JSON files directly into JavaScript objects.
Question 22: How does Node.js handle module caching?
- A. It deletes cached modules after 60 seconds.
- B. Modules are cached in memory after their first load, returning the identical cached instance on subsequent require() calls. β (correct answer)
- C. Caching is disabled by default on production servers.
- D. It saves modules to local database tables.
Explanation: Module caching ensures code inside modules runs once, maintaining singleton state easily.
Question 23: What is the function of the readline core module?
- A. Reading text files line-by-line using buffer streams.
- B. Providing an interface for reading input streams (like terminal prompts) line-by-line. β (correct answer)
- C. Styling console command outputs.
- D. Validating REST endpoints.
Explanation: readline interacts with process.stdin, making terminal-interactive command-line interfaces easy.
Question 24: Why is the http.Agent class important in Node.js client requests?
- A. It routes requests through proxy domains.
- B. It manages database transaction tables.
- C. It manages connection pooling and reuse for HTTP clients, optimizing TCP handshake latency. β (correct answer)
- D. It compiles HTML stylesheets.
Explanation: Agent pools sockets to destination hosts, allowing connection reuse for consecutive requests.
Question 25: Which command installs a package as a development dependency only?
- A. npm install package --dev
- B. npm install package --save-dev β (correct answer)
- C. npm install package --prod
- D. npm install package -d
Explanation: --save-dev (or -D) saves the package under devDependencies in package.json.
Question 26: What does process.exit(1) mean?
- A. Restart the active node server.
- B. Terminate the process immediately, indicating an error occurred (non-zero status code). β (correct answer)
- C. Clear session files from RAM.
- D. Redirect execution to the next worker thread.
Explanation: Exit code 0 indicates success. Any non-zero status represents an error to shell environments.
Question 27: What is the purpose of the NODE_ENV environment variable?
- A. Setting the version of Node.js to execute.
- B. Standardizing application modes (typically 'development' or 'production') to toggle logs, compilation, and error handling. β (correct answer)
- C. Restricting port range bindings.
- D. Directing database index checks.
Explanation: Frameworks inspect NODE_ENV to disable diagnostic stack traces and enable cache in production.
Question 28: Which core module handles cryptography and data hashing operations?
- A. crypto β (correct answer)
- B. hash
- C. security
- D. os
Explanation: The crypto module provides wraps for OpenSSL, supporting cipher, decipher, and hash functions.
Question 29: What is the difference between path.resolve() and path.join()?
- A. path.resolve() always returns an absolute path, while path.join() combines segments using the current layout format. β (correct answer)
- B. path.join() checks if the file exists on disk.
- C. path.resolve() works only on Unix-based servers.
- D. There is no difference; they are aliases.
Explanation: path.resolve behaves like a sequence of cd commands, resolving segments to absolute directories.
Question 30: How do you capture uncaught sync exceptions globally in Node.js?
- A. Wrapping all codes in a try-catch block.
- B. Listening to the 'uncaughtException' event on the process object. β (correct answer)
- C. Configuring the local system firewall.
- D. Using promises exclusively.
Explanation: Listening to 'uncaughtException' intercepts fatal sync bugs, allowing clean logging before exit.