The file starts with "Start\n", so it ends with a newline.
Step 2: Analyze each append operation
First append adds "Entry1\n" after existing content, second adds "Entry2" after that.
Step 3: Combine all content
Resulting content is "Start\nEntry1\nEntry2" exactly as appended.
Final Answer:
Start\nEntry1\nEntry2 -> Option D
Quick Check:
Appending adds text at end preserving old content [OK]
Hint: Appending adds text exactly where called, watch newlines [OK]
Common Mistakes:
Assuming append overwrites
Ignoring newlines in appended text
Thinking append removes initial content
4. Identify the error in this code snippet that tries to append text to a file:
import fs from 'fs/promises';
fs.appendFile('data.txt', 'New line');
console.log('Appended');
medium
A. Wrong method name, should be writeFile instead of appendFile
B. File path 'data.txt' is invalid without full path
C. Missing await before fs.appendFile causing asynchronous issue
D. Console.log should be inside a callback function
Solution
Step 1: Check usage of async function
fs.appendFile returns a promise and should be awaited or handled.
Step 2: Identify missing await
Without await, appendFile runs asynchronously and may not finish before console.log.
Final Answer:
Missing await before fs.appendFile causing asynchronous issue -> Option C
Quick Check:
Async fs calls need await or then [OK]
Hint: Always await async fs.promises methods [OK]
Common Mistakes:
Forgetting await on async file operations
Confusing appendFile with writeFile
Assuming console.log waits for append
5. You want to append multiple log entries to a file, each on a new line, using Node.js 'fs/promises'. Which approach correctly ensures each entry is on its own line?
hard
A. Use readFile to read, then append entries in memory, then writeFile
B. Use appendFile with '\n' at the end of each entry string
C. Use appendFile without '\n' and rely on file system to add new lines
D. Use writeFile to overwrite file with all entries joined by '\n'
Solution
Step 1: Understand appending multiple entries
Appending adds text exactly as given, so newlines must be included explicitly.
Step 2: Choose method to add new lines
Adding '\n' at the end of each entry ensures each appears on its own line.
Step 3: Compare other options
writeFile overwrites, appendFile without '\n' joins lines, readFile + writeFile is inefficient.
Final Answer:
Use appendFile with '\n' at the end of each entry string -> Option B
Quick Check:
Newline needed to separate appended lines [OK]
Hint: Add '\n' explicitly to each appended string [OK]