









































































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
An advanced review guide emphasizing Node.js services architecture, APIs, event-driven design, and backend performance strategies. Offers concise concept reviews, exam-style questions, and practical examples aimed at strengthening service-level development knowledge.
Typology: Exams
1 / 81
This page cannot be seen from the preview
Don't miss anything!










































































Question 1. Which Node.js feature allows non‑blocking I/O operations? A) Synchronous callbacks B) Event loop C) Global interpreter lock D) Multi‑threaded kernel Answer: B Explanation: The event loop enables Node.js to perform I/O without blocking the single‑threaded JavaScript execution. Question 2. In async/await syntax, what does the await keyword return? A) A resolved promise value B) The original promise object C) The promise’s rejection reason D) Nothing, it just pauses execution Answer: A Explanation: await pauses the async function until the promise resolves and then returns the resolved value. Question 3. Which error type should be handled with a process.on('uncaughtException') listener? A) SyntaxError in source code B) Operational error from a failed I/O call C) Programmer error that was not caught D) Validation error from a schema library Answer: C Explanation: uncaughtException catches errors that were never caught, typically programmer mistakes. Question 4. When using streams, which method is recommended for piping multiple streams together while handling errors?
A) stream.pipe() only B) stream.concat() C) stream.pipeline() D) stream.chain() Answer: C Explanation: stream.pipeline() automatically forwards errors and closes all streams correctly. Question 5. How do you emit a custom event named orderCreated on an EventEmitter instance called emitter? A) emitter.send('orderCreated') B) emitter.emit('orderCreated') C) emitter.trigger('orderCreated') D) emitter.dispatch('orderCreated') Answer: B Explanation: emit is the method used to fire custom events on an EventEmitter. Question 6. Which core module provides the createServer function for HTTP servers? A) net B) fs C) http D) url Answer: C Explanation: The http module contains http.createServer() to start an HTTP server. Question 7. Which status code indicates that the client sent a request with missing required fields? A) 200 B) 301 C) 400
Explanation: Providing key and cert (or pfx) in the options creates an HTTPS server. Question 11. In Express, which method adds a middleware that runs for every request? A) app.use() B) app.all() C) app.route() D) app.handle() Answer: A Explanation: app.use() registers middleware that is invoked for all matching routes. Question 12. Which Express middleware parses URL‑encoded bodies? A) express.json() B) express.urlencoded({ extended: false }) C) express.bodyParser() D) express.text() Answer: B Explanation: express.urlencoded() parses bodies with application/x-www-form-urlencoded content type. Question 13. In Fastify, how do you register a plugin that should be scoped to a specific route? A) fastify.register(plugin, { prefix: '/api' }) B) fastify.use(plugin) C) fastify.mount(plugin, '/api') D) fastify.attach(plugin, '/api') Answer: A Explanation: register with a prefix creates a scoped encapsulation for that route. Question 14. Which Fastify hook runs before the request is validated against a schema?
A) onRequest B) preHandler C) preValidation D) onSend Answer: C Explanation: preValidation occurs after onRequest but before schema validation. Question 15. What is the purpose of defining a JSON schema for a Fastify route? A) To generate TypeScript types automatically B) To validate incoming payloads and serialize responses C) To encrypt the request body D) To enable server‑side rendering Answer: B Explanation: Fastify uses JSON schemas for request validation and response serialization. Question 16. Which library provides a modern fetch‑compatible client for Node.js? A) request B) axios C) undici D) node-fetch Answer: C Explanation: undici is the official high‑performance HTTP client for Node.js and implements the fetch API. Question 17. When making an external HTTP call with undici, which option sets a timeout of 5 seconds? A) { timeout: 5000 } B) { deadline: 5000 }
Answer: B Explanation: Input validation ensures malicious operators (e.g., $gt) cannot be injected into queries. Question 21. Which Express middleware adds common security headers like X‑Content‑Type‑Options and Content‑Security‑Policy? A) helmet() B) cors() C) compression() D) morgan() Answer: A Explanation: helmet sets several HTTP headers to help protect the app from well‑known web vulnerabilities. Question 22. In a Node.js test suite using Jest, which function creates a mock for an HTTP request made by undici? A) jest.mock('undici') B) nock('http://example.com') C) sinon.stub(undici, 'request') D) mockFetch() Answer: A Explanation: jest.mock can replace the entire undici module with a mock implementation. Question 23. Which command starts a Node.js process with the built‑in inspector listening on port 9229? A) node --debug B) node --inspect=9229 app.js C) node --profile app.js D) node --trace-warnings app.js Answer: B
Explanation: --inspect enables the V8 inspector; you can optionally specify the port. Question 24. What is the primary benefit of using a process manager like PM2 for a Node.js service? A) Automatic code minification B) Automatic restarts on crashes and clustering C) Built‑in ORM capabilities D) Real‑time front‑end rendering Answer: B Explanation: PM2 can restart crashed processes, manage multiple instances, and provide logs. Question 25. Which Node.js core module is used to read a TLS private key from the filesystem? A) crypto B) tls C) fs D) path Answer: C Explanation: The fs module reads files, such as keys and certificates, from disk. Question 26. In the context of Node.js streams, what does the highWaterMark option control? A) Maximum number of simultaneous listeners B) Buffer size before back‑pressure is applied C) Number of CPU cores the stream can use D) Timeout for idle streams Answer: B Explanation: highWaterMark defines the internal buffer limit; exceeding it triggers back‑pressure. Question 27. Which of the following is not a valid way to create a promise manually?
C) ajv: { customOptions: { removeAdditional: false } } D) skipValidation: true Answer: D Explanation: skipValidation tells Fastify to bypass schema checks for that route. Question 31. Which Node.js global provides a way to schedule a callback after the current event loop turn? A) setTimeout(fn, 0) B) process.nextTick(fn) C) setImmediate(fn) D) Both B and C are valid Answer: D Explanation: Both process.nextTick and setImmediate schedule callbacks after the current phase, with subtle ordering differences. Question 32. In Express, what does the next('route') call do inside a middleware? A) Passes control to the next middleware in the stack B) Skips remaining middleware for the current route and proceeds to the next matching route C) Triggers an error handler D) Sends a 404 response automatically Answer: B Explanation: next('route') tells Express to bypass remaining handlers for the current route and look for the next route definition. Question 33. Which npm script hook runs automatically after npm install? A) preinstall B) postinstall C) prepublish D) prepare
Answer: B Explanation: postinstall is executed after the package and its dependencies are installed. Question 34. Which of the following statements about Node.js worker threads is true? A) They share the same event loop as the main thread. B) They can be used to offload CPU‑intensive tasks. C) They replace the need for the event loop. D) They are automatically created for each async I/O operation. Answer: B Explanation: Worker threads run in separate V8 isolates, making them suitable for CPU‑heavy work without blocking the main event loop. Question 35. Which method of the http.ServerResponse object sends a status code and ends the response with a string body? A) writeHead() B) end() C) write() D) send() Answer: B Explanation: res.end([data]) can include a body and implicitly finalizes the response; the status code must be set beforehand via statusCode or writeHead. Question 36. Which of the following is the correct way to enable HTTP/2 in a Node.js server? A) Use the http2 module with http2.createSecureServer() B) Set protocol: 'h2' in the http module options C) Use express() with a special flag D) HTTP/2 is not supported in Node.js yet Answer: A
Explanation: preHandler(request, reply, done) receives done to signal completion. Question 40. Which npm package is most commonly used for request/response mocking in unit tests? A) sinon B) nock C) proxyquire D) rewire Answer: B Explanation: nock intercepts outgoing HTTP calls and provides mock responses. Question 41. Which of the following is the correct way to declare a read‑only property on an object in strict mode? A) Object.defineProperty(obj, 'prop', { value: 5, writable: false }) B) obj.prop = 5; Object.freeze(obj); C) Object.seal(obj); D) Object.preventExtensions(obj); Answer: A Explanation: defineProperty with writable: false creates a read‑only descriptor. Question 42. Which Fastify lifecycle hook runs after the response has been serialized but before it is sent to the client? A) onSend B) preSerialization C) onResponse D) onError Answer: A Explanation: onSend allows modification of the serialized payload right before transmission.
Question 43. In Express, which method is used to programmatically trigger a 404 Not Found error? A) res.notFound() B) next() with no arguments after all routes C) next(createError(404)) D) res.sendStatus(404) Answer: C Explanation: Passing an error (e.g., created by http-errors) to next invokes the error‑handling middleware. Question 44. Which of the following statements about process.env is true? A) It automatically encrypts values stored in it. B) It is mutable at runtime, allowing you to add or change variables. C) It is read‑only; you cannot modify it after the process starts. D) It only contains variables defined in .env files. Answer: B Explanation: process.env is a mutable object; you can set or change properties during execution. Question 45. Which HTTP header is used to protect against click‑jacking attacks? A) X-Frame-Options B) X-XSS-Protection C) X-Content-Type-Options D) Strict-Transport-Security Answer: A Explanation: X-Frame-Options tells browsers whether the page may be displayed in a frame. Question 46. Which of the following is the correct way to create a reusable Express router for /api/users endpoints? A) app.use('/api/users', require('./users'))
D) Encode them with Base64 and store in the repository. Answer: B Explanation: Environment variables keep secrets out of the codebase and can be managed securely per environment. Question 50. Which of the following npm commands installs a package and adds it to devDependencies? A) npm install lodash B) npm install lodash --save-dev C) npm install lodash --save D) npm install lodash - g Answer: B Explanation: The --save-dev flag records the package under devDependencies in package.json. Question 51. What does the cluster module allow you to do in a Node.js application? A) Run multiple processes that share the same server port. B) Create multiple threads inside a single process. C) Automatically load‑balance HTTP requests across different machines. D) Convert callbacks into promises. Answer: A Explanation: cluster forks worker processes that can all listen on the same port, enabling simple scaling. Question 52. Which of the following is the correct way to set a cookie in an Express response? A) res.setHeader('Set-Cookie', 'token=abc; HttpOnly') B) res.cookie('token', 'abc', { httpOnly: true }) C) res.write('Set-Cookie: token=abc') D) Both A and B are valid Answer: D
Explanation: Express provides res.cookie as a helper, but setting the header manually also works. Question 53. In Fastify, which property on the route options defines the expected shape of the request body? A) params B) querystring C) body D) validationSchema Answer: C Explanation: The body property of the schema object describes the expected request payload. Question 54. Which Node.js core module provides utilities for working with file and directory paths? A) url B) path C) fs D) os Answer: B Explanation: The path module offers methods like join, resolve, and basename. Question 55. Which of the following statements about the async_hooks module is true? A) It can be used to trace asynchronous resources throughout their lifecycle. B) It replaces the need for EventEmitter. C) It provides built‑in promise cancellation. D) It automatically optimizes CPU usage. Answer: A Explanation: async_hooks lets you monitor creation, execution, and destruction of async resources.
A) Memory leak B) Event loop blockage C) Code injection leading to remote code execution D) Increased latency Answer: C Explanation: eval executes arbitrary code, making it a vector for code injection attacks. Question 60. Which of these Fastify plugins is used to serve static files? A) fastify-static B) fastify-files C) fastify-serve D) fastify-assets Answer: A Explanation: fastify-static provides middleware to serve files from a directory. Question 61. In Express, which method can be used to set the HTTP status code without sending a body? A) res.status(204) B) res.sendStatus(204) C) res.code(204) D) Both A and B set the status, but only B also ends the response. Answer: D Explanation: res.status sets the code and returns the response object for chaining; res.sendStatus sets the code and sends the corresponding text. Question 62. Which of the following is the correct way to enable gzip compression in an Express app? A) app.use(compression()) after installing the compression package. B) app.enable('gzip')
C) app.use(express.gzip()) D) app.set('compress', true) Answer: A Explanation: The compression middleware handles gzip/deflate automatically. Question 63. Which of the following functions can be used to convert a callback‑based fs.readFile into a promise? A) util.promisify(fs.readFile) B) fs.promises.readFile (built‑in) C) Both A and B are valid D) Neither; you must wrap it manually. Answer: C Explanation: Node.js provides fs.promises.readFile and util.promisify can also create a promise‑based version. Question 64. Which of these is a recommended practice when handling unhandled promise rejections in a production Node.js service? A) Ignore them; they will be logged automatically. B) Register a process.on('unhandledRejection') handler that logs and exits. C) Convert them to synchronous exceptions. D) Set --strict flag at runtime. Answer: B Explanation: Capturing unhandledRejection allows you to log details and shut down gracefully to avoid undefined states. Question 65. Which HTTP header is used by the server to indicate the MIME type of the response body? A) Content-Type B) Accept