Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Appending Text to a File in Node.js
📖 Scenario: You are building a simple Node.js script to keep a log of user actions. Each time a user performs an action, you want to add a new line to a log file without deleting the old entries.
🎯 Goal: Create a Node.js script that appends a new log entry to an existing file called userlog.txt. If the file does not exist, it should be created automatically.
📋 What You'll Learn
Use the built-in fs module to work with files
Create a variable called logEntry with the exact string 'User logged in\n'
Create a variable called filename with the exact string 'userlog.txt'
Use fs.appendFile to add logEntry to filename
Handle errors by logging 'Error writing to file' if any occur
💡 Why This Matters
🌍 Real World
Appending to log files is common in real applications to keep track of user actions, errors, or system events without losing previous data.
💼 Career
Understanding how to work with files and handle asynchronous operations in Node.js is essential for backend development and building reliable server-side applications.
Progress0 / 4 steps
1
Set up the log entry text
Create a variable called logEntry and set it to the string 'User logged in\n' exactly.
Node.js
Hint
Use const to declare logEntry and include the newline character \n at the end.
2
Set the filename variable
Create a variable called filename and set it to the string 'userlog.txt' exactly.
Node.js
Hint
Use const to declare filename with the exact string.
3
Import the fs module
Add a line at the top to import the built-in fs module using import fs from 'fs';.
Node.js
Hint
Use ES module syntax to import fs.
4
Append the log entry to the file
Use fs.appendFile to add logEntry to filename. Provide a callback that logs 'Error writing to file' if an error occurs.
Node.js
Hint
Use fs.appendFile(filename, logEntry, callback) and check if err is truthy inside the callback.
Practice
(1/5)
1. What does appending to a file mean in Node.js?
easy
A. Adding new content to the end of the existing file without removing old content
B. Replacing the entire file content with new data
C. Deleting the file before writing new content
D. Reading the file content without changing it
Solution
Step 1: Understand the meaning of appending
Appending means adding data to the end of existing content without deleting it.
Step 2: Compare with other file operations
Replacing or deleting would remove old content, which is not appending.
Final Answer:
Adding new content to the end of the existing file without removing old content -> Option A
Quick Check:
Appending = add to end [OK]
Hint: Appending means add at the end, not replace [OK]
Common Mistakes:
Confusing append with overwrite
Thinking append deletes old content
Mixing append with read operation
2. Which of these is the correct way to append text to a file using Node.js 'fs/promises' module?
easy
A. await fs.appendFile('file.txt', 'Hello World');
B. await fs.writeFile('file.txt', 'Hello World');
C. await fs.readFile('file.txt', 'Hello World');
D. await fs.deleteFile('file.txt', 'Hello World');
Solution
Step 1: Identify the correct method for appending
The method to add content at the end is 'appendFile' in 'fs/promises'.
Step 2: Check the syntax
Using 'await fs.appendFile(filename, data)' is the correct syntax.
Final Answer:
await fs.appendFile('file.txt', 'Hello World'); -> Option A
Quick Check:
appendFile appends text [OK]
Hint: Use appendFile, not writeFile, to add content [OK]
Common Mistakes:
Using writeFile which overwrites
Using readFile or deleteFile which don't append
Forgetting to await the promise
3. What will be the content of 'log.txt' after running this code if 'log.txt' initially contains "Start\n"?
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]