Unit 1 - Practice Quiz

INT222 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is Node.js?

Introducing Node.JS Easy
A. A front-end JavaScript framework for building user interfaces.
B. A JavaScript runtime built on Chrome's V8 JavaScript engine.
C. A programming language that compiles to JavaScript.
D. A database management system.

2 Which command would you use in a terminal to check if Node.js is installed and to see its version number?

Installing Node.js Easy
A. js --version
B. npm version
C. node -v
D. node check

3 What does REPL stand for in the context of Node.js?

Using Node.js Read Evaluate Print Loop (REPL) Easy
A. Run-Execute-Program-Loop
B. Read-Evaluate-Print-Loop
C. Read-Execute-Parse-Line
D. Run-Evaluate-Process-Logic

4 What is the primary role of npm in the Node.js ecosystem?

Node Package Manager (npm) Easy
A. To manage third-party packages and project dependencies.
B. To run JavaScript code directly in the terminal.
C. To compile Node.js code into machine code.
D. To create new JavaScript files.

5 Which command is used to create a package.json file in a Node.js project?

Initialize Node js project using npm init Easy
A. npm start
B. node new
C. npm init
D. npm create-package

6 Which of the following is an example of a core module in Node.js?

NPM modules (Core Modules, Local Modules, Third Party Modules) Easy
A. react
B. http
C. express
D. lodash

7 In Node.js, what is the fundamental purpose of the EventEmitter class?

EventEmitter in Node.js Easy
A. To read and write files from the disk.
B. To manage network connections.
C. To facilitate communication between objects through events.
D. To parse JSON data.

8 What is a callback function in the context of asynchronous Node.js operations?

Callbacks in Node.js Easy
A. A special type of function that does not take any arguments.
B. A function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
C. A function that is called immediately when it is defined.
D. A function that can only be called once.

9 The I/O (Input/Output) model of Node.js is primarily...

Handling Data I/O in Node.js Easy
A. Exclusively for memory operations
B. Multi-threaded and parallel
C. Asynchronous and non-blocking
D. Synchronous and blocking

10 Which fs module method is used to read the contents of a file synchronously?

Working with fs module Easy
A. fs.createReadStream()
B. fs.open()
C. fs.readFileSync()
D. fs.readFile()

11 How do you convert a JSON string into a JavaScript object?

Working with JSON Easy
A. JSON.convert()
B. JSON.toObject()
C. JSON.parse()
D. JSON.stringify()

12 What is a primary benefit of using streams to handle large files in Node.js?

Using Stream Module to Stream Data Easy
A. They process data in chunks, preventing high memory usage.
B. They execute faster than any other I/O method.
C. They automatically compress the file data.
D. They are the only way to read files in Node.js.

13 Which Node.js core module provides compression and decompression functionality?

Compressing and Decompressing Data with Zlib Easy
A. crypto
B. buffer
C. fs
D. zlib

14 In an async function, what does the await keyword do?

Promises and async/await Easy
A. It defines the start of an asynchronous operation.
B. It pauses the execution of the function until a Promise is settled (resolved or rejected).
C. It converts a callback function into a Promise.
D. It immediately rejects the Promise.

15 If you create a file named my-utils.js in your project and use require('./my-utils.js') to include it, what type of module is this?

NPM modules (Core Modules, Local Modules, Third Party Modules) Easy
A. Third-Party Module
B. Core Module
C. Local Module
D. Global Module

16 How can you exit the Node.js REPL?

Using Node.js Read Evaluate Print Loop (REPL) Easy
A. Close the terminal window
B. Press Ctrl + C twice or type .exit
C. Press Esc
D. Type quit()

17 What is the purpose of the package.json file?

Initialize Node js project using npm init Easy
A. To store metadata about the project and list its dependencies.
B. To contain the main application logic.
C. To lock the exact versions of dependencies for consistent installs.
D. To configure the Node.js runtime.

18 Which command installs a package and adds it to the dependencies section of your package.json file?

Node Package Manager (npm) Easy
A. npm init <package-name>
B. npm install <package-name>
C. npm get <package-name>
D. npm add <package-name>

19 A JavaScript Promise can be in one of three states. Which of the following is NOT one of those states?

Promises and async/await Easy
A. Executing
B. Rejected
C. Fulfilled
D. Pending

20 What is the first argument typically passed to a callback function in asynchronous fs module methods like fs.readFile()?

Working with fs module Easy
A. The file path
B. The data read from the file
C. A boolean indicating success
D. An error object (or null if no error occurred)

21 A web application is designed to handle thousands of concurrent connections for a real-time chat service, where most of the time is spent waiting for user messages. Why is Node.js's architecture particularly well-suited for this I/O-bound task?

Introducing Node.JS Medium
A. Because it has a built-in library for creating user interfaces, which simplifies chat application development.
B. Because its single-threaded, event-driven, non-blocking I/O model allows the server to handle other requests while waiting for I/O operations to complete.
C. Because it uses a multi-threaded model to handle each connection, ensuring high CPU utilization.
D. Because it compiles JavaScript directly to machine code, resulting in faster execution than any other server-side language.

22 A developer needs to use the nodemon tool to automatically restart their server during development. They want to be able to run nodemon from any directory in their terminal, not just within a single project. Which npm command should they use?

Node Package Manager (npm) Medium
A. npm install nodemon
B. npm add nodemon
C. npm install nodemon -g
D. npm install nodemon --save-dev

23 After running npm init -y, you add the following to your package.json:

"scripts": {
"start": "node index.js"
}

If you then run npm start in your terminal, what is the direct consequence?

Initialize Node js project using npm init Medium
A. It installs all dependencies listed in package.json.
B. It executes the command node index.js.
C. It starts the Node.js REPL in the current directory.
D. It checks for outdated packages and suggests updates.

24 Consider the following code snippet in a file named app.js:
javascript
const path = require('path');
const express = require('express');
const myUtils = require('./utils.js');

Assuming the project was set up correctly, how would you classify path, express, and myUtils respectively?

NPM modules (Core Modules, Local Modules, Third Party Modules) Medium
A. Core Module, Third Party Module, Local Module
B. Third Party Module, Core Module, Local Module
C. Local Module, Core Module, Third Party Module
D. Core Module, Local Module, Third Party Module

25 What will be the output of the following Node.js code?
javascript
const EventEmitter = require('events');
const myEmitter = new EventEmitter();

myEmitter.on('greet', (name) => console.log(Hello, ${name}!));
myEmitter.on('greet', () => console.log('Welcome!'));

myEmitter.emit('greet', 'Alice');

EventEmitter in Node.js Medium
A. Welcome!
B. Hello, Alice!
C. Welcome! followed by Hello, Alice!
D. Hello, Alice! followed by Welcome!

26 Examine the code below. How many times will "Event triggered!" be printed to the console?
javascript
const EventEmitter = require('events');
const myEmitter = new EventEmitter();

myEmitter.once('specialEvent', () => {
console.log('Event triggered!');
});

myEmitter.emit('specialEvent');
myEmitter.emit('specialEvent');
myEmitter.emit('specialEvent');

EventEmitter in Node.js Medium
A. 1
B. 3
C. 2
D. 0

27 A developer writes the following code to read a file, process its data, and then write to another file.
javascript
fs.readFile('input.txt', 'utf8', (err, data) => {
if (err) { / handle error / }
processData(data, (err, processed) => {
if (err) { / handle error / }
fs.writeFile('output.txt', processed, (err) => {
if (err) { / handle error / }
console.log('Done!');
});
});
});

This nested structure is often referred to as "Callback Hell" or the "Pyramid of Doom". What is the primary issue this pattern introduces?

Callbacks in Node.js Medium
A. It is impossible to handle errors at each step.
B. It blocks the event loop, making the application unresponsive.
C. It makes the code hard to read, reason about, and maintain.
D. It uses significantly more memory than synchronous code.

28 In Node.js, many asynchronous functions use the "error-first" callback pattern. Given the function signature fs.readFile(path, (err, data) => { ... }), what is the correct way to implement the callback to ensure robust error handling?

Callbacks in Node.js Medium
A. fs.readFile('file.txt', (data, err) => { if(err) { console.error('Error:', err); return; } console.log(data); });
B. fs.readFile('file.txt', (err, data) => { try { console.log(data); } catch (err) { console.error('Error:', err); } });
C. fs.readFile('file.txt', (err, data) => { console.log(data); if(err) throw err; });
D. fs.readFile('file.txt', (err, data) => { if (err) { console.error('Error:', err); return; } console.log(data); });

29 What will be the output of the following Node.js script, assuming message.txt exists and is readable?
javascript
const fs = require('fs');

console.log('Start');
const data = fs.readFileSync('message.txt', 'utf8');
console.log('File content read');
console.log('End');

Working with fs module Medium
A. The output order is non-deterministic.
B. Start -> File content read -> End
C. An error will be thrown because readFileSync is deprecated.
D. Start -> End -> File content read

30 Contrast the synchronous version with this script that uses the asynchronous fs.readFile(). What is the most likely output?
javascript
const fs = require('fs');

console.log('Start');
fs.readFile('message.txt', 'utf8', (err, data) => {
console.log('File content read');
});
console.log('End');

Working with fs module Medium
A. Start -> End -> File content read
B. The output is non-deterministic and could be in any order.
C. Start -> File content read -> End
D. End -> Start -> File content read

31 You need to log application events to a file named app.log. Each new log entry should be added to the end of the file without deleting existing content. Which fs method is most suitable for this task?

Working with fs module Medium
A. fs.createWriteStream(path)
B. fs.appendFile(path, data, callback)
C. fs.writeFile(path, data, callback)
D. fs.writeFileSync(path, data)

32 You have a file config.json with the content: {"port": 8080, "host": "localhost"}. Consider the following code:
javascript
const fs = require('fs');

fs.readFile('./config.json', 'utf8', (err, data) => {
if (err) throw err;
// What code is needed here to access config properties?
const config = // ... mystery code ...
console.log(config.port);
});

What must the mystery code be for the script to run without errors and log 8080?

Working with JSON Medium
A. JSON.parse(data)
B. require(data)
C. JSON.stringify(data)
D. data

33 You need to process a very large log file (e.g., 5GB) on a machine with limited RAM (e.g., 1GB). Why is using fs.createReadStream() preferable to fs.readFile() in this scenario?

Using Stream Module to Stream Data Medium
A. fs.createReadStream() automatically parses the file content, making it easier to work with.
B. fs.createReadStream() uses less memory because it reads the file in small, manageable chunks instead of loading the entire file into RAM at once.
C. fs.createReadStream() is faster because it reads the entire file in parallel.
D. fs.readFile() is deprecated and should not be used for large files.

34 In the context of Node.js streams, what is the core function of the .pipe() method as shown below?
javascript
const readableStream = fs.createReadStream('input.txt');
const writableStream = fs.createWriteStream('output.txt');
readableStream.pipe(writableStream);

Using Stream Module to Stream Data Medium
A. It connects the output of a Readable stream to the input of a Writable stream, automatically managing the flow of data and backpressure.
B. It duplicates the readableStream into another writableStream.
C. It converts the data from the readableStream into a different format for the writableStream.
D. It waits for the readableStream to finish and then writes all its data to the writableStream in one go.

35 You want to compress a file named large.log into large.log.gz using streams for memory efficiency. Which of the following code snippets correctly accomplishes this?

Compressing and Decompressing Data with Zlib Medium
A. javascript
const fs = require('fs');
const zlib = require('zlib');
fs.createReadStream('large.log')
.pipe(fs.createWriteStream('large.log.gz'))
.pipe(zlib.createGzip());
B. javascript
const fs = require('fs');
const zlib = require('zlib');
zlib.createGzip()
.pipe(fs.createReadStream('large.log'))
.pipe(fs.createWriteStream('large.log.gz'));
C. javascript
const fs = require('fs');
const zlib = require('zlib');
fs.createReadStream('large.log')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('large.log.gz'));
D. javascript
const fs = require('fs');
const zlib = require('zlib');
const data = fs.readFileSync('large.log');
zlib.gzip(data, (err, compressed) => {
fs.writeFileSync('large.log.gz', compressed);
});

36 To serve compressed assets to a web browser, a Node.js server needs to decompress a .gz file on the fly and stream it to the client. Which zlib transform stream should be used in the pipeline to handle the decompression?

Compressing and Decompressing Data with Zlib Medium
A. zlib.createInflate()
B. zlib.createGzip()
C. zlib.createBrotliDecompress()
D. zlib.createGunzip()

37 How can the following callback-based function be correctly refactored using the async/await syntax, leveraging the fs.promises API?
javascript
// Original function
const fs = require('fs');
function getFileData(path, callback) {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
return callback(err, null);
}
callback(null, data);
});
}

Promises and async/await Medium
A. javascript
const fs = require('fs').promises;
function getFileData(path) {
await fs.readFile(path, 'utf8');
}
B. javascript
const fs = require('fs').promises;
function getFileData(path) {
return new Promise((resolve, reject) => {
const data = fs.readFile(path, 'utf8');
resolve(data);
});
}
C. javascript
const fs = require('fs').promises;
async function getFileData(path) {
return fs.readFile(path, 'utf8', (err, data) => data);
}
D. javascript
const fs = require('fs').promises;
async function getFileData(path) {
const data = await fs.readFile(path, 'utf8');
return data;
}

38 What is the standard and most idiomatic way to handle potential errors when using await on a Promise that might reject inside an async function?
javascript
async function fetchData() {
// How to handle a potential rejection from riskyOperation()?
const data = await riskyOperation();
console.log('Success:', data);
}

Promises and async/await Medium
A. By checking a special error property on the result: if (data.error) { ... }
B. By using .catch() directly on the await keyword: await riskyOperation().catch(err => ...);
C. By passing a second callback function to await: await riskyOperation(onSuccess, onError);
D. By wrapping the await call in a try...catch block.

39 In a Node.js stream pipeline, such as readable.pipe(writable), what is the concept of "backpressure"?

Using Stream Module to Stream Data Medium
A. A mechanism where the operating system signals that the file is too large to be read into memory.
B. An error that occurs when two streams in a pipe have incompatible data formats.
C. A signal from a slow writable stream to a fast readable stream to pause sending data until the writable stream is ready for more.
D. When a writable stream writes data back to the readable stream.

40 What is the primary purpose of the package-lock.json file in a Node.js project?

NPM modules (Core Modules, Local Modules, Third Party Modules) Medium
A. It locks the versions of all dependencies, including sub-dependencies, ensuring that every npm install results in the exact same node_modules tree.
B. It contains the scripts and metadata for the project, while package.json contains only the dependencies.
C. It is a backup of package.json that is used if the main file is corrupted.
D. It is a human-readable list of project dependencies, meant for developers to review.

41 Consider the following Node.js code snippet using EventEmitter. What will be the final output to the console?

javascript
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

myEmitter.on('newListener', (event, listener) => {
if (event === 'data') {
console.log('A new "data" listener is being added!');
myEmitter.on('data', () => console.log('Listener added from within newListener'));
}
});

myEmitter.on('data', () => console.log('Initial data listener.'));

myEmitter.emit('data');

EventEmitter in Node.js Hard
A. A new "data" listener is being added!
Initial data listener.
B. Initial data listener.
Listener added from within newListener
A new "data" listener is being added!
C. The program enters an infinite loop and crashes with a 'Maximum call stack size exceeded' error.
D. A new "data" listener is being added!
Initial data listener.
Listener added from within newListener

42 Analyze the following asynchronous code. In what order will the numbers be logged to the console?

javascript
async function async1() {
console.log(1);
await async2();
console.log(2);
}

async function async2() {
console.log(3);
}

console.log(4);

setTimeout(() => {
console.log(5);
}, 0);

async1();

new Promise((resolve) => {
console.log(6);
resolve();
}).then(() => {
console.log(7);
});

console.log(8);

Promises and async/await Hard
A. 1, 3, 4, 6, 8, 2, 7, 5
B. 4, 1, 3, 6, 8, 2, 7, 5
C. 4, 1, 3, 2, 6, 8, 7, 5
D. 4, 1, 3, 6, 8, 7, 2, 5

43 You are piping a Readable stream to a Writable stream that is much slower. The high water mark of the Readable stream is 16KB. What is the primary mechanism that prevents the Readable stream from overwhelming the Writable stream and consuming excessive memory?

javascript
// slowWritable is a Writable stream that processes data very slowly.
fastReadable.pipe(slowWritable);

Using Stream Module to Stream Data Hard
A. The Readable stream automatically detects the Writable stream's speed and adjusts its read rate.
B. The operating system kernel's pipe buffer automatically blocks the fastReadable process until slowWritable has consumed data.
C. The pipe() method automatically pauses the Writable stream when its internal buffer is full.
D. The Writable stream's write() method returns false when its buffer is full, which signals the Readable stream to stop pushing data via the 'drain' event mechanism.

44 Consider two modules, a.js and b.js, with a circular dependency. What is logged to the console when a.js is executed with node a.js?

a.js:
javascript
console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done =', b.done);
exports.done = true;
console.log('a done');


b.js:
javascript
console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done =', a.done);
exports.done = true;
console.log('b done');

NPM modules (Core, Local, Third Party) Hard
A. a starting
b starting
in b, a.done = undefined
b done
in a, b.done = true
a done
B. The program throws a 'Maximum call stack size exceeded' error due to the circular require.
C. a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
D. a starting
b starting
in a, b.done = true
a done
in b, a.done = true
b done

45 What is the output of the following script? Analyze the interaction between process.nextTick() and setImmediate() within an I/O callback.

javascript
const fs = require('fs');

fs.readFile(__filename, () => {
console.log('readFile');
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
});

Callbacks in Node.js Hard
A. readFile
timeout
immediate
nextTick
B. readFile
immediate
nextTick
timeout
C. readFile
nextTick
immediate
timeout
D. readFile
nextTick
timeout
immediate

46 You are creating a file compression pipeline using streams. Which of the following statements correctly identifies the primary advantage of using stream.pipeline over multiple .pipe() calls?

// Method A: .pipe()
readable.pipe(gzip).pipe(writable);

// Method B: stream.pipeline()
pipeline(readable, gzip, writable, (err) => { ... });

Compressing and Decompressing Data with Zlib Hard
A. pipeline provides better compression ratios for large files.
B. pipeline properly forwards and handles errors from any stream in the chain, preventing memory leaks from unclosed file descriptors, whereas .pipe() does not.
C. pipeline automatically handles backpressure more efficiently than .pipe().
D. pipeline runs the stream operations in a separate thread, improving performance.

47 What is a critical difference between fs.watch() and fs.watchFile() regarding their underlying implementation and performance implications?

fs module Hard
A. fs.watchFile() can watch directories recursively, whereas fs.watch() cannot.
B. fs.watch() is deprecated, while fs.watchFile() is the modern standard.
C. fs.watch() uses platform-specific, efficient OS mechanisms (like inotify on Linux), while fs.watchFile() periodically polls the file's stats, making it less efficient and more resource-intensive.
D. fs.watch() provides more reliable event types ('rename', 'change') across all platforms compared to fs.watchFile().

48 In a project with an existing package.json and package-lock.json, you run npm install. A teammate simultaneously adds a new dependency, updates the package-lock.json on their branch, and merges it to main. You pull the changes and run npm install again. What is the most likely outcome, and how does it differ from running npm ci in the same scenario?

Node Package Manager (npm) Hard
A. npm install might update packages based on semantic versioning rules in package.json, potentially modifying package-lock.json. npm ci will throw an error if package.json and package-lock.json are out of sync.
B. npm install may ignore the new package-lock.json and attempt to resolve dependencies from package.json, potentially creating a new lock file. npm ci will fail if node_modules exists.
C. npm install will update your node_modules based on the new package-lock.json. npm ci would do the same thing.
D. npm install will read the new package-lock.json, update node_modules to match it exactly, and not modify the lock file. npm ci will delete node_modules and then perform the same installation.

49 You need to process a 5GB JSON file containing a single large array of objects. Which approach is most memory-efficient and avoids crashing the Node.js process?


// large-data.json
[
{ "id": 1, "data": "..." },
{ "id": 2, "data": "..." },
// ...millions of objects
]

Working with JSON Hard
A. Use fs.createReadStream, read the data in chunks, concatenate them into a string, and then call JSON.parse().
B. Use fs.readFileSync to read the entire file into a buffer, then call JSON.parse().
C. Use require('./large-data.json') to leverage Node's optimized JSON parsing.
D. Use fs.createReadStream piped to a streaming JSON parsing library (e.g., JSONStream or oboe.js) to process objects one by one.

50 What is the output of this async/await code block, and why?

javascript
async function test() {
console.log('start');
const result = await 'a non-promise value';
console.log(result);
console.log('end');
}
test();
console.log('after call');

Promises and async/await Hard
A. start
a non-promise value
end
after call
B. The code throws a TypeError because you can only await a Promise.
C. start
after call
end
a non-promise value
D. start
after call
a non-promise value
end

51 You run the following commands sequentially in the Node.js REPL. What will be the value of the special variable _ (underscore) after the final line executes?


> const fs = require('fs');
undefined
> let x = 10;
undefined
> fs.readFile('/etc/passwd', (err, data) => { console.log('File read complete'); });
undefined
> x * 5

Using Node.js Read Evaluate Print Loop (REPL) Hard
A. 50
B. A Promise object for the fs.readFile operation.
C. A Buffer containing the contents of /etc/passwd
D. undefined

52 What happens in Node.js if you require() the same module using two different but valid paths that resolve to the identical file?

javascript
// a.js
const module1 = require('./module.js');
const module2 = require('/full/path/to/project/module.js'); // Assuming this is the absolute path to module.js

console.log(module1 === module2);

// module.js
module.exports = { id: Math.random() };

NPM modules (Core, Local, Third Party) Hard
A. It depends on the operating system's handling of file paths (case-sensitivity).
B. true, because Node.js resolves the path to its canonical absolute path and caches the module based on that resolved path.
C. false, because Node.js caches modules based on the string path provided to require().
D. The code throws an error because the same module cannot be loaded twice.

53 What is the behavior of an EventEmitter if an 'error' event is emitted but there are no listeners registered for the 'error' event?

EventEmitter in Node.js Hard
A. The error event is queued until a listener is attached.
B. It throws an unhandled exception, and if not caught by a domain or process.on('uncaughtException'), the Node.js process will crash.
C. A warning is printed to stderr but the program continues.
D. The error is silently ignored and the program continues.

54 You are building a high-throughput network server that receives large binary data chunks. Which I/O approach would typically result in the lowest latency and least event loop blockage for processing each individual incoming chunk?

Handling Data I/O in Node.js Hard
A. Using worker_threads to offload the I/O operations from the main thread.
B. Using asynchronous stream-based processing with Transform streams to process data as it arrives.
C. Aggregating chunks in a memory buffer and processing them when a certain size is reached.
D. Using fs.writeFileSync to save each chunk to a temporary file.

55 When running npm init, you are prompted for several fields like 'name', 'version', and 'description'. Where does npm source the default values for 'author', 'email', and 'license' that it suggests during this process?

Initialize Node js project using npm init Hard
A. From the global package.json file located in the system's root directory.
B. From environment variables named NPM_USER, NPM_EMAIL, and NPM_LICENSE.
C. They are hardcoded defaults in the npm binary and cannot be changed.
D. From the user's .npmrc configuration file, typically located in the user's home directory.

56 Consider the following code that writes to a file using a file descriptor. What is a significant risk associated with this pattern, especially in a long-running application with error conditions?

javascript
const fs = require('fs');

fs.open('logfile.txt', 'a', (err, fd) => {
if (err) throw err;

// Some complex, potentially failing logic here
const buffer = Buffer.from('log entry\n');
fs.write(fd, buffer, (err) => {
if (err) {
// What happens to fd here on a write error?
}
// Where should fs.close be called?
});
});

fs module Hard
A. If a write error occurs or the logic contains an unhandled exception, fs.close(fd) might never be called, leading to a file descriptor leak.
B. The 'a' flag (append) prevents any write errors, so this pattern is safe.
C. Node.js automatically closes all open file descriptors when the callback function finishes executing.
D. The file descriptor fd will be automatically closed by the garbage collector when it goes out of scope.

57 What will be logged to the console when the following code is executed? Pay close attention to the behavior of Promise.all and Promise.allSettled when promises reject.

javascript
const p1 = Promise.resolve(1);
const p2 = Promise.reject('Error 2');
const p3 = Promise.resolve(3);

async function test() {
try {
const resAll = await Promise.all([p1, p2, p3]);
console.log('all:', resAll);
} catch (err) {
console.log('all_err:', err);
}

try {
const resAllSettled = await Promise.allSettled([p1, p2, p3]);
console.log('allSettled:', resAllSettled.map(r => r.status));
} catch (err) {
console.log('allSettled_err:', err);
}
}

test();

Promises and async/await Hard
A. all: [ 1, undefined, 3 ]
allSettled: [ 'fulfilled', 'rejected', 'fulfilled' ]
B. The second try/catch block for Promise.allSettled is never reached due to the rejection.
C. all_err: Error 2
allSettled: [ 'fulfilled', 'rejected', 'fulfilled' ]
D. all_err: Error 2
allSettled_err: Error 2

58 What is the primary purpose of the peerDependencies field in a package.json file, and how does its enforcement differ in modern npm (v7+) compared to older versions (v3-6)?

Node Package Manager (npm) Hard
A. It is an alias for devDependencies, and its behavior has not changed between npm versions.
B. It expresses a dependency on a 'host' package, expecting the consumer of the library to provide it. Modern npm (v7+) automatically installs them by default, while older versions only issued a warning.
C. It specifies dependencies that are only required for development, and modern npm installs them automatically.
D. It is a list of exact versions of dependencies that are required for the package to work, and modern npm enforces this with strict version matching.

59 You are implementing a custom Transform stream. What is the explicit role of the callback function passed as the second argument to the _transform method?

javascript
class MyTransform extends Transform {
_transform(chunk, encoding, callback) {
// ... processing logic ...
this.push(processedChunk);
callback();
}
}

Using Stream Module to Stream Data Hard
A. To signal that the current chunk has been fully processed and the stream is ready for the next chunk.
B. To push the transformed data chunk to the downstream Writable stream.
C. To signal an error to the upstream Readable stream.
D. To pause the stream to wait for an external resource.

60 What is a potential side effect of a library function that violates the Node.js error-first callback convention by invoking the callback multiple times, and why is this problematic?

javascript
function unreliable(callback) {
if (Math.random() > 0.5) {
callback(null, 'Success');
}
callback(new Error('Failure')); // Also called unconditionally
}

unreliable((err, result) => {
if (err) {
console.error(err.message);
return;
}
console.log(result);
});

Callbacks in Node.js Hard
A. The second invocation will be ignored by the JavaScript runtime.
B. The program will throw a TypeError because a callback can only be invoked once.
C. It can lead to unpredictable application state and logic being executed multiple times. For example, both the success (console.log) and error (console.error) paths could be executed for a single call.
D. It creates a memory leak by keeping the callback in the event queue indefinitely.