




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This practice exam thoroughly tests Node.js fundamentals, event-driven architecture, asynchronous programming patterns, module system behavior, performance profiling, security best practices, native addons, and release governance. Exercises include implementing Node-based services, debugging runtime issues, contributing patches, and understanding how Node.js technical governance operates under the OpenJS Foundation.
Typology: Exams
1 / 132
This page cannot be seen from the preview
Don't miss anything!





























































































Question 1. Which phase of the Node.js event loop handles callbacks scheduled by setTimeout and setInterval? A) Poll B) Timers C) Check D) Close Answer: B Explanation: The Timers phase processes callbacks whose timer has expired, which includes those scheduled by setTimeout and setInterval. Question 2. What is the primary difference between process.nextTick() and setImmediate()? A) process.nextTick() runs after I/O callbacks, setImmediate() runs before. B) process.nextTick() runs before the next event loop iteration, setImmediate() runs on the following iteration’s check phase. C) process.nextTick() schedules a timer, setImmediate() schedules a promise. D) Both are identical; they just have different names. Answer: B Explanation: process.nextTick() callbacks are executed immediately after the current operation, before the event loop continues, while setImmediate() callbacks are queued to run in the check phase of the next loop iteration. Question 3. Which Buffer method creates a new Buffer from a UTF‑8 string? A) Buffer.alloc() B) Buffer.from() C) Buffer.concat()
D) Buffer.slice() Answer: B Explanation: Buffer.from(string, 'utf8') creates a Buffer containing the UTF‑8 encoded bytes of the given string. Question 4. When concatenating two Buffers buf1 and buf2, which call is correct? A) Buffer.concat([buf1, buf2]) B) buf1.concat(buf2) C) buf1 + buf2 D) Buffer.merge(buf1, buf2) Answer: A Explanation: Buffer.concat() takes an array of Buffers and returns a new Buffer containing their combined data. Question 5. In an EventEmitter, which method registers a listener that is invoked at most once? A) on() B) addListener() C) once() D) emit() Answer: C Explanation: once(event, listener) registers a listener that automatically removes itself after the first invocation. Question 6. What will the following code output?
## Exam Answer: A Explanation: Backpressure is the mechanism where a writable stream signals the readable stream to pause when it cannot accept more data, preventing memory overload. **Question 9.** Which method is used to watch for changes on a file or directory? A) `fs.watchFile()` B) `fs.watch()` C) `fs.monitor()` D) `fs.observe()` Answer: B Explanation: `fs.watch()` registers a listener for change events on a file or directory. **Question 10.** What is the difference between `fs.readFileSync()` and `fs.readFile()`? A) `readFileSync` returns a promise, `readFile` does not. B) `readFileSync` blocks the event loop, `readFile` uses a callback and is non‑blocking. C) `readFileSync` works only on Windows, `readFile` works cross‑platform. D) There is no difference; they are aliases. Answer: B Explanation: The synchronous version blocks the event loop until the file is read, while the asynchronous version uses a callback and allows other operations to continue. **Question 11.** Which of the following is the correct error‑first callback signature? A) `(err, data) => {}` B) `(data, err) => {}` C) `(error) => {}` ## Exam D) `(result) => {}` Answer: A Explanation: Node.js conventions use the first argument for the error (`err`) and the second for the result (`data`). **Question 12.** Which Promise method resolves when **all** supplied promises have settled, regardless of rejection? A) `Promise.all()` B) `Promise.race()` C) `Promise.allSettled()` D) `Promise.any()` Answer: C Explanation: `Promise.allSettled()` returns a promise that fulfills after every input promise has either fulfilled or rejected, providing their status. **Question 13.** What does `Promise.any()` return if all input promises are rejected? A) It resolves with the first rejection reason. B) It rejects with an `AggregateError`. C) It resolves with `undefined`. D) It never settles. Answer: B Explanation: When all promises reject, `Promise.any()` rejects with an `AggregateError` containing all rejection reasons. **Question 14.** Which utility converts a callback‑based function to return a promise? A) `util.promisify` ## Exam A) `const utils = require('./utils.mjs');` B) `import utils from './utils.mjs';` C) `import * as utils from './utils.mjs';` D) `export utils from './utils.mjs';` Answer: B Explanation: `import utils from './utils.mjs'` imports the default export of an ES module. **Question 18.** What does the spread operator (`...`) do when used in a function call? A) It creates a shallow copy of the object. B) It expands an iterable into individual arguments. C) It merges two objects into one. D) It binds a function to a new `this` value. Answer: B Explanation: Using `...iterable` in a call spreads the elements of the iterable as separate arguments. **Question 19.** Which of the following statements about lexical scoping in JavaScript is correct? A) Functions can access variables defined after their declaration. B) Variables are scoped to the block in which they are declared, regardless of `var`. C) Inner functions have access to variables of their outer functions. D) `let` and `const` are function‑scoped, not block‑scoped. Answer: C Explanation: Lexical scoping means a function retains access to the variables in its outer (enclosing) scopes at the time of definition. ## Exam **Question 20.** In the prototype chain, which object sits at the top for most user‑defined objects? A) `Object.prototype` B) `Function.prototype` C) `Array.prototype` D) `null` Answer: A Explanation: All objects ultimately inherit from `Object.prototype`; its prototype is `null`. **Question 21.** Which `process` property provides access to environment variables? A) `process.argv` B) `process.env` C) `process.cwd` D) `process.title` Answer: B Explanation: `process.env` is an object containing the user’s environment variables. **Question 22.** How can a Node.js application listen for a termination signal (`SIGTERM`)? A) `process.on('exit', handler)` B) `process.on('SIGTERM', handler)` C) `process.once('kill', handler)` D) `process.on('terminate', handler)` Answer: B Explanation: The `process` object emits a `'SIGTERM'` event when the process receives that signal. ## Exam Answer: B Explanation: `os.totalmem()` provides the total system memory. **Question 26.** How can you retrieve the list of network interfaces using the `os` module? A) `os.networkInterfaces()` B) `os.getNetworkInfo()` C) `os.interfaces()` D) `os.netInfo()` Answer: A Explanation: `os.networkInterfaces()` returns an object describing each network interface. **Question 27.** Which CLI flag starts the Node.js inspector on default port 9229? A) `--debug` B) `--inspect` C) `-i` D) `--trace` Answer: B Explanation: `node --inspect` launches the V8 inspector, allowing debugging tools to attach. **Question 28.** What does the `-e` flag do when running Node.js? A) Executes a script file. B) Evaluates the following string as JavaScript code. C) Enables ECMAScript modules. D) Starts the REPL in silent mode. Answer: B ## Exam Explanation: `node - e "code"` evaluates the provided string as a script. **Question 29.** Which HTTP status code is appropriate for a successful `POST` request that creates a resource? A) 200 OK B) 201 Created C) 202 Accepted D) 204 No Content Answer: B Explanation: 201 indicates that a new resource has been successfully created. **Question 30.** In an HTTP server created with the `http` module, which method is used to send a response header? A) `res.writeHeader()` B) `res.setHeader()` C) `res.sendHeader()` D) `res.header()` Answer: B Explanation: `res.setHeader(name, value)` sets a response header before the body is sent. **Question 31.** Which of the following is a common mitigation against HTTP Parameter Pollution? A) Using `eval()` on query strings. B) Whitelisting expected parameters and ignoring duplicates. C) Concatenating all parameters into a single string. D) Disabling URL encoding. ## Exam const http = require('http'); http.createServer((req,res)=>{res.end('Hello World');}).listen(3000); B) ```js const http = require('http'); http.listen(3000,()=>{console.log('Hello World');});
C) ```js const http = require('http'); http.createServer().listen(3000,()=>{res.end('Hello World');}); D) ```js const http = require('http'); const server = http.Server(); server.on('request', (req,res)=>{res.end('Hello World');}); server.listen(3000);
Answer: A Explanation: `http.createServer()` returns a server instance; the callback receives `req` and `res`, and `res.end()` sends the response. The server then listens on the given port. **Question 35.** What does the `pipeline` utility from the `stream` module help prevent? A) Duplicate event emissions. B) Unhandled promise rejections. C) Memory leaks caused by uncaught errors in streams. ## Exam D) Synchronous I/O blocking. Answer: C Explanation: `pipeline()` automatically forwards errors and closes all streams, reducing the chance of memory leaks. **Question 36.** Which of the following statements about `fs.promises` is correct? A) It provides synchronous versions of file system methods. B) It returns callbacks instead of promises. C) It offers promise‑based equivalents of the `fs` methods. D) It is deprecated in Node.js 20. Answer: C Explanation: `fs.promises` exposes the same operations as `fs` but returns promises, enabling async/await usage. **Question 37.** In a Node.js project, which field in `package.json` specifies the entry point for `require()` when the package is imported? A) `"main"` B) `"scripts"` C) `"bin"` D) `"module"` Answer: A Explanation: `"main"` tells Node which file to load when the package is required. **Question 38.** Which semantic versioning range `^1.2.3` allows? A) Any version >=1.2.3 and <2.0. B) Any version >=1.2.3 and <=1.2. ## Exam A) It returns a promise. B) It invokes a callback with `(err, result)`. C) It returns an EventEmitter. D) It logs the result to console. Answer: B Explanation: `util.callbackify(promiseFn)` converts a promise‑returning function into one that uses the error‑first callback pattern. **Question 42.** In an Express middleware, calling `next(err)` has what effect? A) Skips all remaining middleware and sends a default 200 response. B) Passes control to the next error‑handling middleware. C) Terminates the request without a response. D) Logs the error and continues as normal. Answer: B Explanation: Supplying an error to `next` tells Express to skip regular middleware and invoke the first error‑handling middleware (functions with four arguments). **Question 43.** Which of the following is a correct way to read JSON from a file synchronously? A) `fs.readFileSync('data.json', 'utf8')` B) `fs.readFile('data.json', JSON.parse)` C) `fs.readFileSync('data.json').toJSON()` D) `fs.readFileSync('data.json', { encoding: 'json' })` Answer: A Explanation: Reading the file as a UTF‑8 string returns the JSON text; you would then `JSON.parse` it (parsing step omitted for brevity). ## Exam **Question 44.** What does the `--experimental-modules` flag enable in older Node.js versions? A) Support for ES modules using `.mjs` extension. B) The ability to import JSON files directly. C) Automatic transpilation of TypeScript. D) Enabling the V8 inspector. Answer: A Explanation: The flag activates experimental support for ECMAScript modules before they became stable. **Question 45.** Which of the following is the correct way to handle uncaught exceptions globally? A) `process.on('unhandledRejection', handler)` B) `process.on('uncaughtException', handler)` C) `process.on('error', handler)` D) `process.on('exit', handler)` Answer: B Explanation: `uncaughtException` fires when an exception bubbles out of the call stack without being caught. **Question 46.** Which method of the `http` module is used to make an outgoing HTTP GET request? A) `http.request()` B) `http.get()` C) `http.fetch()` ## Exam const { Transform } = require('stream'); const upper = Transform({ upperCase: true }); D) ```js const upper = new Transform(); upper.upperCase = true;
Answer: A Explanation: A Transform stream requires a `transform` function that processes each chunk and calls the callback with the transformed data. **Question 49.** What will `process.cwd()` return? A) The directory of the Node.js executable. B) The current working directory of the process. C) The directory of the script being executed. D) The home directory of the user. Answer: B Explanation: `process.cwd()` gives the directory from which the Node.js process was launched. **Question 50.** Which of the following is true about `cluster` module? A) It creates multiple processes that share the same event loop. B) It allows a single Node.js process to use multiple CPU cores by forking workers. C) It provides a way to spawn threads within a single process. D) It is deprecated in Node.js 18. Answer: B ## Exam Explanation: The `cluster` module forks the main process, creating worker processes that can run on separate CPU cores. **Question 51.** Which statement correctly describes the behavior of `fs.watchFile()` compared to `fs.watch()`? A) `watchFile` uses polling, while `watch` uses OS native events. B) `watchFile` is faster than `watch`. C) Both use the same underlying mechanism. D) `watchFile` works only on Windows. Answer: A Explanation: `fs.watchFile()` polls the file for changes, whereas `fs.watch()` relies on the operating system’s file‑system events. **Question 52.** In an async function, what does `return` implicitly do? A) Returns a resolved promise with the given value. B) Returns the value directly, blocking the event loop. C) Throws an error if the value is not a promise. D) Ignores the value and returns `undefined`. Answer: A Explanation: An async function always returns a promise; returning a non‑promise value resolves the promise with that value. **Question 53.** Which of the following is a correct way to handle a rejected promise using async/await? A) `await fn(); catch(err => console.error(err));` B) `try { await fn(); } catch (err) { console.error(err); }`