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 programming language that compiles to JavaScript.
B. A front-end JavaScript framework for building user interfaces.
C. A JavaScript runtime built on Chrome's V8 JavaScript engine.
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. node check
C. node -v
D. npm version

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

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

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

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

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 create-package
B. npm init
C. node new
D. npm start

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. express
B. react
C. http
D. lodash

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

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

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 that is called immediately when it is defined.
C. 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.
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. Synchronous and blocking
D. Asynchronous and non-blocking

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

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

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

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

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 automatically compress the file data.
C. They execute faster than any other I/O method.
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. zlib
C. fs
D. buffer

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

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

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. Core Module
B. Local Module
C. Global Module
D. Third-Party Module

16 How can you exit the Node.js REPL?

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

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

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

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 get <package-name>
B. npm add <package-name>
C. npm init <package-name>
D. npm install <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. Fulfilled
B. Executing
C. Rejected
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 data read from the file
B. The file path
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 it uses a multi-threaded model to handle each connection, ensuring high CPU utilization.
C. Because it compiles JavaScript directly to machine code, resulting in faster execution than any other server-side language.
D. 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.

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 --save-dev
B. npm add nodemon
C. npm install nodemon -g
D. npm install nodemon

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 starts the Node.js REPL in the current directory.
B. It executes the command node index.js.
C. It checks for outdated packages and suggests updates.
D. It installs all dependencies listed in package.json.

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, Local Module, Third Party Module
B. Third Party Module, Core Module, Local Module
C. Local Module, Core Module, Third Party Module
D. Core Module, Third Party Module, Local 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. Hello, Alice!
B. Hello, Alice! followed by Welcome!
C. Welcome!
D. Welcome! followed by Hello, Alice!

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. 3
B. 1
C. 0
D. 2

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 makes the code hard to read, reason about, and maintain.
B. It uses significantly more memory than synchronous code.
C. It is impossible to handle errors at each step.
D. It blocks the event loop, making the application unresponsive.

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', (err, data) => { 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', (data, err) => { 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. Start -> End -> File content read
B. An error will be thrown because readFileSync is deprecated.
C. The output order is non-deterministic.
D. Start -> File content read -> End

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. End -> Start -> File content read
B. The output is non-deterministic and could be in any order.
C. Start -> File content read -> End
D. Start -> End -> 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.writeFile(path, data, callback)
C. fs.writeFileSync(path, data)
D. fs.appendFile(path, data, callback)

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.stringify(data)
B. require(data)
C. data
D. JSON.parse(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.readFile() is deprecated and should not be used for large files.
C. fs.createReadStream() is faster because it reads the entire file in parallel.
D. fs.createReadStream() uses less memory because it reads the file in small, manageable chunks instead of loading the entire file into RAM at once.

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 waits for the readableStream to finish and then writes all its data to the writableStream in one go.
B. It connects the output of a Readable stream to the input of a Writable stream, automatically managing the flow of data and backpressure.
C. It duplicates the readableStream into another writableStream.
D. It converts the data from the readableStream into a different format for the writableStream.

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(zlib.createGzip())
.pipe(fs.createWriteStream('large.log.gz'));
B. 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);
});
C. javascript
const fs = require('fs');
const zlib = require('zlib');
fs.createReadStream('large.log')
.pipe(fs.createWriteStream('large.log.gz'))
.pipe(zlib.createGzip());
D. javascript
const fs = require('fs');
const zlib = require('zlib');
zlib.createGzip()
.pipe(fs.createReadStream('large.log'))
.pipe(fs.createWriteStream('large.log.gz'));

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;
async function getFileData(path) {
return fs.readFile(path, 'utf8', (err, data) => data);
}
C. javascript
const fs = require('fs').promises;
function getFileData(path) {
return new Promise((resolve, reject) => {
const data = fs.readFile(path, 'utf8');
resolve(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 using .catch() directly on the await keyword: await riskyOperation().catch(err => ...);
B. By passing a second callback function to await: await riskyOperation(onSuccess, onError);
C. By wrapping the await call in a try...catch block.
D. By checking a special error property on the result: if (data.error) { ... }

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. When a writable stream writes data back to the readable stream.
C. An error that occurs when two streams in a pipe have incompatible data formats.
D. A signal from a slow writable stream to a fast readable stream to pause sending data until the writable stream is ready for more.

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 is a backup of package.json that is used if the main file is corrupted.
B. It contains the scripts and metadata for the project, while package.json contains only the dependencies.
C. It locks the versions of all dependencies, including sub-dependencies, ensuring that every npm install results in the exact same node_modules tree.
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. A new "data" listener is being added!
Initial data listener.
Listener added from within newListener
D. The program enters an infinite loop and crashes with a 'Maximum call stack size exceeded' error.

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. 4, 1, 3, 6, 8, 2, 7, 5
B. 4, 1, 3, 6, 8, 7, 2, 5
C. 4, 1, 3, 2, 6, 8, 7, 5
D. 1, 3, 4, 6, 8, 2, 7, 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 pipe() method automatically pauses the Writable stream when its internal buffer is full.
B. 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.
C. The operating system kernel's pipe buffer automatically blocks the fastReadable process until slowWritable has consumed data.
D. The Readable stream automatically detects the Writable stream's speed and adjusts its read rate.

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. The program throws a 'Maximum call stack size exceeded' error due to the circular require.
B. a starting
b starting
in b, a.done = undefined
b done
in a, b.done = true
a done
C. a starting
b starting
in a, b.done = true
a done
in b, a.done = true
b done
D. a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a 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
nextTick
timeout
immediate
B. readFile
timeout
immediate
nextTick
C. readFile
nextTick
immediate
timeout
D. readFile
immediate
nextTick
timeout

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 automatically handles backpressure more efficiently than .pipe().
B. pipeline provides better compression ratios for large files.
C. pipeline runs the stream operations in a separate thread, improving performance.
D. pipeline properly forwards and handles errors from any stream in the chain, preventing memory leaks from unclosed file descriptors, whereas .pipe() does not.

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

fs module Hard
A. 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.
B. fs.watch() is deprecated, while fs.watchFile() is the modern standard.
C. fs.watchFile() can watch directories recursively, whereas fs.watch() cannot.
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 will update your node_modules based on the new package-lock.json. npm ci would do the same thing.
B. 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.
C. 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.
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.readFileSync to read the entire file into a buffer, then call JSON.parse().
B. Use require('./large-data.json') to leverage Node's optimized JSON parsing.
C. Use fs.createReadStream piped to a streaming JSON parsing library (e.g., JSONStream or oboe.js) to process objects one by one.
D. Use fs.createReadStream, read the data in chunks, concatenate them into a string, and then call JSON.parse().

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
a non-promise value
end
D. start
after call
end
a non-promise value

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. undefined
D. A Buffer containing the contents of /etc/passwd

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. The code throws an error because the same module cannot be loaded twice.
B. false, because Node.js caches modules based on the string path provided to require().
C. It depends on the operating system's handling of file paths (case-sensitivity).
D. true, because Node.js resolves the path to its canonical absolute path and caches the module based on that resolved path.

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. A warning is printed to stderr but the program continues.
B. The error event is queued until a listener is attached.
C. It throws an unhandled exception, and if not caught by a domain or process.on('uncaughtException'), the Node.js process will crash.
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 fs.writeFileSync to save each chunk to a temporary file.
C. Using asynchronous stream-based processing with Transform streams to process data as it arrives.
D. Aggregating chunks in a memory buffer and processing them when a certain size is reached.

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 user's .npmrc configuration file, typically located in the user's home directory.
B. They are hardcoded defaults in the npm binary and cannot be changed.
C. From environment variables named NPM_USER, NPM_EMAIL, and NPM_LICENSE.
D. From the global package.json file located in the system's root 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 file descriptor fd will be automatically closed by the garbage collector when it goes out of scope.
C. Node.js automatically closes all open file descriptors when the callback function finishes executing.
D. The 'a' flag (append) prevents any write errors, so this pattern is safe.

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. The second try/catch block for Promise.allSettled is never reached due to the rejection.
B. all_err: Error 2
allSettled: [ 'fulfilled', 'rejected', 'fulfilled' ]
C. all_err: Error 2
allSettled_err: Error 2
D. all: [ 1, undefined, 3 ]
allSettled: [ 'fulfilled', 'rejected', 'fulfilled' ]

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 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.
C. 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.
D. It specifies dependencies that are only required for development, and modern npm installs them automatically.

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 an error to the upstream Readable stream.
B. To push the transformed data chunk to the downstream Writable stream.
C. To pause the stream to wait for an external resource.
D. To signal that the current chunk has been fully processed and the stream is ready for the next chunk.

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 creates a memory leak by keeping the callback in the event queue indefinitely.
D. 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.