



































































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
A comprehensive preparation guide focused on Node.js application development, covering modules, asynchronous programming, testing, debugging, and performance optimization. The China edition incorporates localized development contexts and exam-focused practice exercises.
Typology: Exams
1 / 75
This page cannot be seen from the preview
Don't miss anything!




































































Question 1. Which keyword creates a block‑scoped variable that cannot be reassigned? A) var B) let C) const D) function Answer: C Explanation: const creates a block‑scoped constant; its binding cannot be reassigned after initialization. Question 2. In JavaScript, what is the result of the expression typeof null? A) "object" B) "null" C) "undefined" D) "function" Answer: A Explanation: Historically, typeof null returns "object" due to a legacy bug in the language. Question 3. Which of the following correctly sets up prototypal inheritance between Animal and Dog using ES5 syntax? A) Dog.prototype = new Animal(); B) Dog.proto = Animal.prototype; C) Object.setPrototypeOf(Dog.prototype, Animal.prototype); D) Dog.prototype = Object.create(Animal.prototype); Answer: D Explanation: Object.create(Animal.prototype) creates a new object whose prototype is Animal.prototype, establishing inheritance without calling the Animal constructor. Question 4. What does a closure allow a function to do? A) Access its own lexical environment after the outer function returns. B) Modify the global object directly. C) Prevent any variable from being garbage‑collected.
D) Execute code synchronously only. Answer: A Explanation: A closure captures variables from its surrounding lexical scope, preserving them even after the outer function finishes execution. Question 5. Arrow functions differ from regular functions because they: A) Have their own arguments object. B) Bind this lexically from the surrounding scope. C) Can be used as constructors. D) Are hoisted to the top of their block. Answer: B Explanation: Arrow functions do not have their own this; they inherit it from the enclosing lexical context. Question 6. Which statement correctly defines a subclass Car that extends a base class Vehicle using ES6 class syntax? A) class Car extends Vehicle {} B) class Car inherits Vehicle {} C) class Car : Vehicle {} D) class Car super Vehicle {} Answer: A Explanation: The extends keyword creates a subclass relationship in ES6 class syntax. Question 7. In Node.js, which pattern is commonly used for handling asynchronous errors in callbacks? A) Throw‑catch block inside the callback. B) Returning an error object as the second argument. C) The “error‑first” callback where the first argument is an error. D) Using console.error and continuing execution. Answer: C Explanation: Node’s convention is that the first argument of a callback is an error (if any), followed by result data.
B) I/O callbacks C) Poll D) Check Answer: D Explanation: The check phase processes callbacks registered via setImmediate(). Question 12. Which of the following correctly creates a Buffer from the string "Node" using UTF‑8 encoding? A) Buffer.from('Node', 'utf8') B) new Buffer('Node', 'utf8') C) Buffer.alloc('Node') D) Buffer.concat('Node') Answer: A Explanation: Buffer.from(string, encoding) creates a new buffer containing the encoded string; 'utf8' is the default encoding. Question 13. Which stream type can be both read from and written to? A) Readable B) Writable C) Duplex D) Transform Answer: C Explanation: Duplex streams implement both the Readable and Writable interfaces. Question 14. What does the pipeline() utility from the stream module help prevent? A) Memory leaks caused by unhandled errors. B) Blocking the event loop with synchronous I/O. C) Data duplication across streams. D) Automatic conversion of object streams to binary. Answer: A
Explanation: pipeline() forwards errors and automatically closes all streams, reducing the risk of unhandled error‑induced memory leaks. Question 15. In a readable stream, what does the highWaterMark option control? A) The maximum number of listeners allowed. B) The size of the internal buffer before the stream stops reading. C) The maximum number of concurrent writes. D) The timeout for each chunk. Answer: B Explanation: highWaterMark defines the threshold (in bytes or objects) at which the internal buffer is considered full, applying backpressure. Question 16. Which method removes all listeners for a specific event on an EventEmitter instance? A) off(eventName) B) removeAllListeners(eventName) C) clearListeners(eventName) D) deleteListeners(eventName) Answer: B Explanation: removeAllListeners(eventName) detaches every listener for the given event. Question 17. How can you emit an error event that will automatically cause a Node.js process to crash if unhandled? A) emitter.emit('error', new Error('boom')) B) emitter.throw(new Error('boom')) C) process.exit(1, new Error('boom')) D) emitter.raise('error', 'boom') Answer: A Explanation: Emitting 'error' on an EventEmitter without a listener triggers an uncaught exception, terminating the process. Question 18. Which fs method reads a file asynchronously and returns a promise when the fs/promises API is used?
D) os.memory.total Answer: A Explanation: os.totalmem() returns the total system memory in bytes; converting to megabytes is a simple division. Question 22. Which process property provides access to command‑line arguments passed to a Node.js script? A) process.argv B) process.env C) process.args D) process.options Answer: A Explanation: process.argv is an array containing the executable path, script path, and any additional arguments. Question 23. How can you gracefully terminate a Node.js process with exit code 0? A) process.exit(1) B) process.kill(process.pid, 'SIGTERM') C) process.exit(0) D) process.abort() Answer: C Explanation: process.exit(0) ends the process, indicating successful execution via the exit code 0. Question 24. Which child_process method is best suited for executing a command that returns a large amount of output without buffering the entire result? A) exec B) execFile C) spawn D) fork Answer: C Explanation: spawn streams stdout and stderr, allowing handling of large outputs without buffering the whole output in memory.
Question 25. When using child_process.exec(), how are the command’s stdout and stderr presented to the callback? A) As separate stream objects. B) As a combined string. C) As separate string arguments (stdout, stderr). D) As a Buffer containing both streams. Answer: C Explanation: The callback receives (error, stdout, stderr) where stdout and stderr are strings containing the respective outputs. Question 26. What is the primary advantage of using child_process.fork() over spawn() for another Node.js script? A) It automatically pipes stdin/stdout to the parent. B) It creates a new V8 instance with shared memory. C) It sets up an IPC channel for message passing. D) It runs the child in a separate OS user. Answer: C Explanation: fork() spawns a new Node process and establishes a built‑in IPC channel, enabling process.send() and process.on('message'). Question 27. Which module should be used to perform CPU‑intensive work without blocking the event loop in modern Node.js? A) child_process only B) worker_threads C) cluster D) fs Answer: B Explanation: worker_threads runs JavaScript in parallel worker threads, allowing CPU‑heavy tasks to execute without blocking the main event loop. Question 28. In CommonJS, what does module.exports = { foo: 'bar' } accomplish? A) It creates a global variable foo.
Explanation: ^1.2.3 permits updates that do not modify the major version (i.e., >=1.2.3 <2.0.0). Question 32. Which core module provides a simple assertion library for testing Node.js code? A) assert B) test C) chai D) expect Answer: A Explanation: The built‑in assert module offers a collection of assertion functions for verifying invariants. Question 33. Which test runner is bundled with Node.js starting from version 18? A) Mocha B) Jest C) node:test D) Tape Answer: C Explanation: Node 18 introduced the experimental node:test module, a built‑in test runner. Question 34. When writing an asynchronous test with Mocha, which of the following signals that the test is complete? A) Returning a boolean. B) Calling done() or returning a promise. C) Using await without done. D) Throwing an error. Answer: B Explanation: Mocha considers a test finished when the done callback is invoked or when a returned promise resolves/rejects. Question 35. Which Node.js flag enables the V8 inspector for debugging? A) --debug
B) --inspect C) --trace D) --profile Answer: B Explanation: node --inspect starts the V8 inspector, allowing connections from Chrome DevTools or other debugging clients. Question 36. What does process.nextTick() schedule? A) A callback after the current poll phase. B) A callback at the start of the next event‑loop iteration. C) A callback after all I/O callbacks have completed. D) A callback after a 0‑ms timeout. Answer: B Explanation: process.nextTick() queues a function to run before the event loop proceeds to the next phase, i.e., at the start of the next iteration. Question 37. Which of the following is true about the require cache? A) It stores compiled modules as strings. B) It can be cleared by deleting the entry from require.cache. C) It is only used for ES modules. D) It automatically reloads a module on each require. Answer: B Explanation: require.cache holds the exported objects of loaded modules; removing an entry forces a fresh load on the next require. Question 38. In a Node.js HTTP server, which method ends the response and sends data to the client? A) res.write() B) res.end() C) res.send() D) res.close() Answer: B
Question 42. In Node.js, what is the default encoding for fs.readFileSync when no encoding is provided? A) utf8 B) ascii C) binary (returns a Buffer) D) base64 Answer: C Explanation: Without an explicit encoding, fs.readFileSync returns a Buffer containing raw binary data. Question 43. Which of the following correctly creates a readable stream from a file named data.txt? A) fs.createReadStream('data.txt') B) fs.readFile('data.txt') C) fs.openReadStream('data.txt') D) stream.read('data.txt') Answer: A Explanation: fs.createReadStream returns a Readable stream for the specified file. Question 44. What does the transform stream method _transform(chunk, encoding, callback) need to do? A) Push the transformed data and call callback() when done. B) Return the transformed chunk directly. C) Emit a data event manually. D) Modify the original chunk object in place. Answer: A Explanation: Inside _transform, the implementation must push transformed data (via this.push) and invoke callback to signal completion. Question 45. Which event is emitted by a writable stream when it has flushed all buffered data to the underlying resource? A) drain B) finish
C) close D) end Answer: B Explanation: The finish event indicates that end() has been called and all data has been written. Question 46. When using stream.pipeline(source, transform, destination, callback), what happens if one of the streams emits an error? A) The error is ignored. B) The pipeline automatically destroys all streams and calls the callback with the error. C) Only the source stream is destroyed. D) The error propagates to the process’s uncaughtException. Answer: B Explanation: pipeline handles errors by cleaning up all streams and invoking the final callback with the error argument. Question 47. Which of the following statements about process.env is correct? A) It is a plain JavaScript object that can be directly modified to affect the environment of the parent process. B) Changes to process.env are persisted across restarts of the Node.js application. C) It contains only environment variables defined at the time the process started. D) It is read‑only and cannot be changed at runtime. Answer: A Explanation: process.env is mutable; assigning to it updates the environment for the current process and its child processes, but not the parent shell. Question 48. Which method of the os module returns an array of objects describing each CPU core? A) os.cpus() B) os.cpuInfo() C) os.getCPUs() D) os.processors() Answer: A
B) It runs in a separate thread. C) The callback is placed on the timers phase and may be delayed by other pending operations. D) It blocks the event loop until the timer expires. Answer: C Explanation: setTimeout schedules a callback for the timers phase; the actual execution may be later if the event loop is busy. Question 53. What does the util.promisify function do? A) Converts a callback‑based function into one that returns a promise. B) Turns a promise into a callback style. C) Creates a new promise that resolves after a delay. D) Serializes a promise to JSON. Answer: A Explanation: util.promisify(fn) returns a version of fn that returns a promise instead of using a callback. Question 54. Which of the following correctly parses a JSON string safely, catching syntax errors? A) JSON.parse(data) B) try { JSON.parse(data) } catch(e) {} C) JSON.safeParse(data) D) eval('(' + data + ')') Answer: B Explanation: Wrapping JSON.parse in a try/catch handles malformed JSON without throwing uncaught exceptions. Question 55. When using fs.createWriteStream, which option disables the automatic opening of the file? A) { autoClose: false } B) { lazy: true } C) { flags: 'a' } D) { start: 0 }
Answer: A Explanation: Setting autoClose: false prevents the stream from automatically closing (and thus opening) the file descriptor; you must manage it manually. Question 56. Which method of the http module creates a client request? A) http.createServer() B) http.request() C) http.get() D) Both B and C Answer: D Explanation: http.request() creates a generic request; http.get() is a convenience wrapper that calls request with the method set to GET. Question 57. In a Node.js application, which environment variable is commonly used to indicate the runtime environment (development, production, etc.)? A) NODE_ENV B) ENVIRONMENT C) APP_MODE D) RUN_MODE Answer: A Explanation: NODE_ENV is a de‑facto standard for distinguishing between development, test, and production modes. Question 58. Which of the following statements about the global object is correct? A) It is automatically imported in every module without require. B) Adding a property to global makes it available as a top‑level variable in all modules. C) It can be deleted with delete global. D) It is the same as window in browsers. Answer: B Explanation: Properties attached to global become globally accessible, though this practice is discouraged.
D) Generates a unique identifier for the process. Answer: A Explanation: process.umask([mask]) gets or sets the file mode creation mask, influencing permission bits for newly created files. Question 63. In a Node.js application, which module would you use to parse command‑line arguments like --port=3000? A) url B) querystring C) process.argv manually D) commander (third‑party) Answer: C Explanation: Node provides process.argv; while third‑party parsers exist, the core way is to inspect and parse this array manually. Question 64. Which of the following is true about fs.promises.mkdir with the { recursive: true } option? A) It creates only the deepest directory, failing if parents are missing. B) It creates all missing parent directories as needed. C) It throws an error if the directory already exists. D) It returns a boolean indicating success. Answer: B Explanation: The recursive flag makes mkdir behave like mkdir - p, creating any missing ancestors. Question 65. What does the url.fileURLToPath() function do? A) Converts a file system path to a URL object. B) Parses a URL string into its components. C) Converts a file: URL to a native file system path. D) Normalizes a path string. Answer: C Explanation: url.fileURLToPath() takes a file: URL and returns the corresponding absolute file system path.
Question 66. Which of the following is NOT a valid way to export multiple values from an ES module? A) export const a = 1, b = 2; B) export { a, b }; C) module.exports = { a, b }; D) export default { a, b }; Answer: C Explanation: module.exports is CommonJS syntax; ES modules use export statements. Question 67. When using the cluster module, how can a worker process send a message to the master? A) process.send(message) B) worker.emit('message', message) C) cluster.send(message) D) process.postMessage(message) Answer: A Explanation: In a clustered worker, process.send() transmits a message over the IPC channel to the master process. Question 68. Which Node.js API would you use to compute a SHA‑256 hash of a string? A) crypto.createHash('sha256').update(data).digest('hex') B) fs.hash('sha256', data) C) crypto.sha256(data) D) hash.sha256(data) Answer: A Explanation: The crypto module’s createHash method creates a hash object; chaining update and digest produces the final hash. Question 69. What does the EventEmitter.listenerCount(emitter, eventName) method return? A) The total number of events emitted so far. B) The number of listeners currently attached to eventName.