




























































































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 exam guide prepares developers for Node.js application development, covering server-side JavaScript, APIs, asynchronous programming, security, performance optimization, and deployment. The guide emphasizes real-world coding scenarios and exam-aligned development exercises.
Typology: Exams
1 / 122
This page cannot be seen from the preview
Don't miss anything!





























































































Question 1. Which of the following statements about the let keyword is true? A) let variables are hoisted and initialized with undefined. B) let variables cannot be redeclared in the same block scope. C) let creates a global variable when used outside any function. D) let variables are accessible before their declaration due to hoisting. Answer: B Explanation: let is block‑scoped and cannot be redeclared within the same block; it is hoisted but remains in the Temporal Dead Zone until its declaration is evaluated. Question 2. In JavaScript, what does the Temporal Dead Zone (TDZ) refer to? A) The period when var variables are inaccessible. B) The time between a block’s entry and the execution of a let/const declaration. C) The interval when garbage collection is paused. D) The phase of the event loop that handles timers. Answer: B Explanation: TDZ is the time from entering a block until the let/const declaration is executed; accessing the variable during TDZ throws a ReferenceError. Question 3. Which of the following expressions results in true due to type coercion? A) 0 == false B) [] === false C) null === undefined D) "" === 0 Answer: A Explanation: Using the abstract equality operator (==), 0 is coerced to false, making the comparison true. Strict equality (===) does not perform coercion.
Question 4. What is the output of the following code?
function outer() { let count = 0; return function inner() { return ++count; }; } const a = outer(); console.log(a()); console.log(a());A) 0 0 B) 1 2 C) 1 1 D) 2 2 Answer: B Explanation: The inner function forms a closure over count. Each call increments and returns the updated value, producing 1 then 2. Question 5. Which statement about JavaScript prototypes is correct? A) Every object has its own copy of prototype methods. B) Prototypes are only used for class inheritance in ES6. C) The [[Prototype]] internal slot points to the object’s prototype.
A) Spread operator B) Rest parameters C) Destructuring assignment D) Template literals Answer: C Explanation: Destructuring lets you unpack values from objects (or arrays) into distinct variables using a syntax that mirrors the structure. Question 9. What will the following code output?
const arr = [1, 2, 3]; const newArr = [...arr, 4]; console.log(newArr);A) [1,2,3] B) [1,2,3,4] C) [[1,2,3],4] D) Error Answer: B Explanation: The spread operator expands the elements of arr into a new array, then 4 is appended, resulting in [1,2,3,4]. Question 10. In Node.js, which phase of the event loop handles timer callbacks scheduled by setTimeout and setInterval? A) Poll B) Timers
C) Check D) Close callbacks Answer: B Explanation: The Timers phase executes callbacks whose timers have expired. Question 11. During which event‑loop phase are I/O callbacks that were deferred to the next loop iteration processed? A) Timers B) Pending callbacks C) Poll D) Check Answer: B Explanation: The Pending callbacks phase runs callbacks for some system operations (e.g., TCP errors) that were deferred. Question 12. What is the primary purpose of the libuv thread pool in Node.js? A) To execute JavaScript code on multiple threads. B) To handle CPU‑intensive calculations. C) To offload blocking I/O operations (e.g., file system, DNS). D) To manage the event‑loop phases. Answer: C Explanation: libuv provides a pool of worker threads to perform blocking operations without blocking the main event loop. Question 13. Which statement accurately describes Node.js’s single‑threaded nature? A) All JavaScript code runs on a single OS thread, but I/O can be processed concurrently.
A) 5 B) 10 C) Oops D) undefined Answer: C Explanation: The error thrown in the second then is caught by the catch, which logs the error message. Question 17. Which of the following statements about async functions is false? A) They always return a promise. B) They can use await only inside their own body. C) They cannot contain return statements. D) Errors thrown inside are converted to rejected promises. Answer: C Explanation: async functions can return values; those values are wrapped in a resolved promise. Question 18. Consider the code:
async function foo() { ## Guide try { await Promise.reject('bad'); } catch (e) { return e; } } foo().then(console.log);What is printed? A) undefined B) bad C) Promise { } D) No output (unhandled rejection) Answer: B Explanation: The rejection is caught, and the caught value 'bad' is returned, which resolves the outer promise with 'bad'. Question 19. Which method creates a custom event emitter that can emit an event named 'dataReady'? A) new EventEmitter().on('dataReady', handler) B) process.emit('dataReady') C) EventTarget.dispatchEvent('dataReady') D) require('events').create('dataReady') Answer: A Explanation: EventEmitter instances can register listeners with .on() and later emit events with .emit().
Explanation: fs.promises.writeFile returns a promise and writes data asynchronously. Question 23. What does fs.watch() do? A) Continuously polls a file for changes. B) Emits events when a file or directory is modified. C) Returns a promise that resolves after the file is changed. D) Locks a file for exclusive access. Answer: B Explanation: fs.watch registers a listener that receives events when the target is altered. Question 24. Which Buffer method creates a new Buffer containing the hexadecimal representation of the string 'test'? A) Buffer.from('test', 'hex') B) Buffer.alloc('test') C) Buffer.from('test') D) Buffer.from('test', 'utf8').toString('hex') Answer: D Explanation: First create a Buffer from the UTF‑8 string, then convert it to a hex string with .toString('hex'). Question 25. In a Node.js stream, which type can both read and write data? A) Readable B) Writable C) Duplex D) Transform Answer: C
Explanation: Duplex streams implement both the Readable and Writable interfaces. Question 26. What is the purpose of stream.pipeline()? A) To concatenate multiple streams into a single string. B) To pipe streams together while handling errors automatically. C) To convert a readable stream into a writable one. D) To create a new Transform stream from two existing streams. Answer: B Explanation: pipeline connects streams and forwards errors to a callback, simplifying cleanup. Question 27. Which path method normalizes the path '/foo/bar//baz/../qux'? A) path.join('/foo/bar//baz/../qux') B) path.resolve('/foo/bar//baz/../qux') C) path.normalize('/foo/bar//baz/../qux') D) path.parse('/foo/bar//baz/../qux') Answer: C Explanation: path.normalize removes redundant separators and resolves .. segments. Question 28. How can you retrieve the number of CPU cores available on the host machine using the os module? A) os.cpus().length B) os.totalmem() C) os.networkInterfaces().length D) os.uptime() Answer: A
Explanation: 201 Created signals that the request resulted in a new resource on the server. Question 32. In the Node.js http module, which method is used to send a response body to the client? A) res.writeHead() B) res.end() C) res.send() D) res.pipe() Answer: B Explanation: res.end([data]) finalizes the response; optionally it can include the body data. Question 33. Which header should be set to allow cross‑origin requests from any domain? A) Content-Type: application/json B) Cache-Control: no-cache C) Access-Control-Allow-Origin: * D) Authorization: Bearer Answer: C Explanation: The Access-Control-Allow-Origin header controls CORS; * permits any origin. Question 34. How can you parse a URL string into its components using the WHATWG URL API? A) new URL(urlString) B) url.parse(urlString) C) require('url').URL(urlString) D) URL.parse(urlString) Answer: A
Explanation: The global URL constructor creates an object with properties like pathname, searchParams, etc. Question 35. In Express, which function signature defines an error‑handling middleware? A) (req, res, next) B) (err, req, res, next) C) (req, res) D) (err, req, res) Answer: B Explanation: Error‑handling middleware must have four parameters, with the first being the error object. Question 36. Which Express method mounts a router at the path /api? A) app.use('/api', router) B) app.get('/api', router) C) app.route('/api').use(router) D) app.mount('/api', router) Answer: A Explanation: app.use attaches middleware or a router to a base path. Question 37. How can you define a route that captures an optional :id parameter in Express? A) app.get('/user/:id?', handler) B) app.get('/user/:id*', handler) C) app.get('/user/:?id', handler) D) app.get('/user/:id+', handler)
Answer: B Explanation: The -D (or --save-dev) flag records the package under devDependencies in package.json. Question 41. In package.json, what does the caret (^) before a version number signify? A) Accept only the exact version. B) Accept patch and minor updates, but not major. C) Accept any newer version. D) Accept only pre‑release versions. Answer: B Explanation: ^1.2.3 allows updates that do not change the left‑most non‑zero digit (major version). Question 42. What is the effect of running npm audit fix? A) It updates all dependencies to their latest versions. B) It automatically applies patches for known vulnerabilities when possible. C) It removes the node_modules folder. D) It generates a new package-lock.json without changes. Answer: B Explanation: npm audit fix attempts to install safe versions of vulnerable packages, modifying the lockfile accordingly. Question 43. Which of the following statements about global vs. local package installation is true? A) Global packages are automatically included in require() calls. B) Local packages are installed in the project’s node_modules directory.
C) Global packages can be listed in dependencies of package.json. D) Local packages are only usable from the command line. Answer: B Explanation: Local packages reside in the project’s node_modules and are resolved by Node’s module algorithm. Question 44. Which testing framework ships with Node.js as of version 18? A) Mocha B) Jest C) node:test D) Tape Answer: C Explanation: Node.js includes the experimental node:test module for writing tests without external dependencies. Question 45. In a Mocha test, which function indicates an asynchronous test that completes when done() is called? A) it('test', async () => {}) B) it('test', function(done) { /*...*/ }) C) it('test', () => { return Promise.resolve(); }) D) it('test') Answer: B Explanation: Providing a done callback tells Mocha to wait until done() is invoked. Question 46. Which Node.js built‑in debugging protocol can be accessed via node -- inspect?
Question 49. What is the main difference between spawn and exec? A) spawn buffers the entire output; exec streams it. B) exec returns a Buffer with the complete output; spawn provides streams. C) spawn can only run Node scripts; exec runs any command. D) exec runs the command in a separate thread. Answer: B Explanation: exec collects the command’s output into a callback‑provided Buffer, while spawn gives you streaming access. Question 50. Which of the following is a recommended practice to mitigate SQL injection in a Node.js application? A) Concatenating user input directly into query strings. B) Using parameterized queries / prepared statements. C) Escaping single quotes manually. D) Disabling the database’s authentication. Answer: B Explanation: Parameterized queries separate code from data, preventing malicious input from altering query structure. Question 51. Which middleware adds common security headers such as X‑Content‑Type‑Options and Strict‑Transport‑Security? A) cors B) helmet C) morgan D) compression
Answer: B Explanation: Helmet sets various HTTP headers to help protect apps from well‑known web vulnerabilities. Question 52. How does a JSON Web Token (JWT) typically convey authentication information? A) As an encrypted payload stored in a cookie. B) As a signed base64‑encoded string containing header, payload, and signature. C) As a plain‑text string sent in the URL. D) As a binary file uploaded to the server. Answer: B Explanation: JWTs consist of three base64url‑encoded parts (header, payload, signature) and are signed to verify integrity. Question 53. Which npm package is commonly used to load environment variables from a .env file? A) dotenv B) config C) envify D) cross-env Answer: A Explanation: dotenv reads key‑value pairs from a .env file and adds them to process.env. Question 54. In Node.js, which of the following correctly creates a readable stream from a file and pipes it to an HTTP response? A) fs.createReadStream('file.txt').pipe(res); B) fs.readFile('file.txt', (err, data) => res.end(data));