Unit 1 - Practice Quiz
1 What is Node.js?
2 Which command would you use in a terminal to check if Node.js is installed and to see its version number?
js --version
npm version
node -v
node check
3 What does REPL stand for in the context of Node.js?
4
What is the primary role of npm in the Node.js ecosystem?
5
Which command is used to create a package.json file in a Node.js project?
npm start
node new
npm init
npm create-package
6 Which of the following is an example of a core module in Node.js?
react
http
express
lodash
7
In Node.js, what is the fundamental purpose of the EventEmitter class?
8 What is a callback function in the context of asynchronous Node.js operations?
9 The I/O (Input/Output) model of Node.js is primarily...
10
Which fs module method is used to read the contents of a file synchronously?
fs.createReadStream()
fs.open()
fs.readFileSync()
fs.readFile()
11 How do you convert a JSON string into a JavaScript object?
JSON.convert()
JSON.toObject()
JSON.parse()
JSON.stringify()
12 What is a primary benefit of using streams to handle large files in Node.js?
13 Which Node.js core module provides compression and decompression functionality?
crypto
buffer
fs
zlib
14
In an async function, what does the await keyword do?
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?
16 How can you exit the Node.js REPL?
Ctrl + C twice or type .exit
Esc
quit()
17
What is the purpose of the package.json file?
18
Which command installs a package and adds it to the dependencies section of your package.json file?
npm init <package-name>
npm install <package-name>
npm get <package-name>
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?
20
What is the first argument typically passed to a callback function in asynchronous fs module methods like fs.readFile()?
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?
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?
npm install nodemon
npm add nodemon
npm install nodemon -g
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?
package.json.
node index.js.
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?
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');
Welcome!
Hello, Alice!
Welcome! followed by Hello, Alice!
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');
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?
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?
fs.readFile('file.txt', (data, err) => { if(err) { console.error('Error:', err); return; } console.log(data); });
fs.readFile('file.txt', (err, data) => { try { console.log(data); } catch (err) { console.error('Error:', err); } });
fs.readFile('file.txt', (err, data) => { console.log(data); if(err) throw err; });
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');
readFileSync is deprecated.
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');
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?
fs.createWriteStream(path)
fs.appendFile(path, data, callback)
fs.writeFile(path, data, callback)
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?
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?
fs.createReadStream() automatically parses the file content, making it easier to work with.
fs.createReadStream() uses less memory because it reads the file in small, manageable chunks instead of loading the entire file into RAM at once.
fs.createReadStream() is faster because it reads the entire file in parallel.
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);
readableStream into another writableStream.
readableStream into a different format for the writableStream.
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?
const fs = require('fs');
const zlib = require('zlib');
fs.createReadStream('large.log')
.pipe(fs.createWriteStream('large.log.gz'))
.pipe(zlib.createGzip());
const fs = require('fs');
const zlib = require('zlib');
zlib.createGzip()
.pipe(fs.createReadStream('large.log'))
.pipe(fs.createWriteStream('large.log.gz'));
const fs = require('fs');
const zlib = require('zlib');
fs.createReadStream('large.log')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('large.log.gz'));
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?
zlib.createInflate()
zlib.createGzip()
zlib.createBrotliDecompress()
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);
});
}
const fs = require('fs').promises;
function getFileData(path) {
await fs.readFile(path, 'utf8');
}
const fs = require('fs').promises;
function getFileData(path) {
return new Promise((resolve, reject) => {
const data = fs.readFile(path, 'utf8');
resolve(data);
});
}
const fs = require('fs').promises;
async function getFileData(path) {
return fs.readFile(path, 'utf8', (err, data) => data);
}
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);
}
error property on the result: if (data.error) { ... }
.catch() directly on the await keyword: await riskyOperation().catch(err => ...);
await: await riskyOperation(onSuccess, onError);
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"?
40
What is the primary purpose of the package-lock.json file in a Node.js project?
npm install results in the exact same node_modules tree.
package.json contains only the dependencies.
package.json that is used if the main file is corrupted.
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');
Initial data listener.
Listener added from within newListener
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);
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);
Readable stream automatically detects the Writable stream's speed and adjusts its read rate.
fastReadable process until slowWritable has consumed data.
pipe() method automatically pauses the Writable stream when its internal buffer is full.
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');
b starting
in b, a.done = undefined
b done
in a, b.done = true
a done
b starting
in b, a.done = false
b done
in a, b.done = true
a done
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'));
});
timeout
immediate
nextTick
immediate
nextTick
timeout
nextTick
immediate
timeout
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) => { ... });
pipeline provides better compression ratios for large files.
pipeline properly forwards and handles errors from any stream in the chain, preventing memory leaks from unclosed file descriptors, whereas .pipe() does not.
pipeline automatically handles backpressure more efficiently than .pipe().
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.watchFile() can watch directories recursively, whereas fs.watch() cannot.
fs.watch() is deprecated, while fs.watchFile() is the modern standard.
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.
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?
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.
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.
npm install will update your node_modules based on the new package-lock.json. npm ci would do the same thing.
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
]
fs.createReadStream, read the data in chunks, concatenate them into a string, and then call JSON.parse().
fs.readFileSync to read the entire file into a buffer, then call JSON.parse().
require('./large-data.json') to leverage Node's optimized JSON parsing.
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');
a non-promise value
end
after call
after call
end
a non-promise value
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
50
Promise object for the fs.readFile operation.
Buffer containing the contents of /etc/passwd
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() };
true, because Node.js resolves the path to its canonical absolute path and caches the module based on that resolved path.
false, because Node.js caches modules based on the string path provided to require().
53
What is the behavior of an EventEmitter if an 'error' event is emitted but there are no listeners registered for the 'error' event?
process.on('uncaughtException'), the Node.js process will crash.
stderr but 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?
worker_threads to offload the I/O operations from the main thread.
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?
package.json file located in the system's root directory.
NPM_USER, NPM_EMAIL, and NPM_LICENSE.
.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.close(fd) might never be called, leading to a file descriptor leak.
'a' flag (append) prevents any write errors, so this pattern is safe.
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();
allSettled: [ 'fulfilled', 'rejected', 'fulfilled' ]
Promise.allSettled is never reached due to the rejection.
allSettled: [ 'fulfilled', 'rejected', 'fulfilled' ]
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)?
devDependencies, and its behavior has not changed between npm versions.
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();
}
}
Writable stream.
Readable stream.
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);
});
TypeError because a callback can only be invoked once.
console.log) and error (console.error) paths could be executed for a single call.