Bird
Raised Fist0
Node.jsframework~20 mins

Appending to files in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
File Append Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Appending text to a file with fs.appendFile
What will be the content of the file 'log.txt' after running this code if the file initially contains 'Hello'? Assume no errors occur.
Node.js
import { appendFileSync, readFileSync } from 'node:fs';

appendFileSync('log.txt', ' World');
const content = readFileSync('log.txt', 'utf8');
console.log(content);
A"Hello World"
B" World"
C"Hello"
D"Hello\n World"
Attempts:
2 left
💡 Hint
Appending adds new content to the end of the existing file content.
Predict Output
intermediate
2:00remaining
Asynchronous file append behavior
What will be logged to the console after running this code snippet?
Node.js
import { appendFile } from 'node:fs';

appendFile('notes.txt', 'New note\n', (err) => {
  if (err) throw err;
  console.log('Note added');
});
console.log('Appending started');
AAppending started\nNote added
BNote added\nAppending started
CAppending started
DNote added
Attempts:
2 left
💡 Hint
Asynchronous functions run their callback after the main thread continues.
🔧 Debug
advanced
2:00remaining
Identifying error in appending to a file
This code is intended to append 'Data' to 'file.txt'. What error will it raise when run?
Node.js
import fs from 'node:fs';

fs.appendFile('file.txt', 'Data', (error) => {
  if (error) throw error;
});

fs.appendFileSync('file.txt', 'More data')
AError: appendFileSync called without encoding
BError: Callback must be a function
CTypeError: fs.appendFile is not a function
DNo error, both append operations succeed
Attempts:
2 left
💡 Hint
Check the usage of appendFile and appendFileSync methods.
component_behavior
advanced
2:00remaining
Effect of encoding on appending files
What will be the content of 'data.txt' after running this code if the file initially contains 'abc'?
Node.js
import { appendFileSync, readFileSync } from 'node:fs';

appendFileSync('data.txt', Buffer.from([0x20, 0x64, 0x65, 0x66]));
const content = readFileSync('data.txt', 'utf8');
console.log(content);
A"abcdef"
B"abc\u0000def"
C"abc def"
D"abc def"
Attempts:
2 left
💡 Hint
Buffer bytes correspond to ASCII characters; 0x20 is a space.
📝 Syntax
expert
3:00remaining
Correct syntax for appending JSON data to a file
Which option correctly appends a JSON string to 'output.json' without overwriting existing content?
A
import { appendFile } from 'node:fs';
appendFile('output.json', JSON.stringify({a:1}), () => {});
B
import { appendFileSync } from 'node:fs';
appendFileSync('output.json', JSON.stringify({a:1}) + '\n');
C
import { writeFileSync } from 'node:fs';
writeFileSync('output.json', JSON.stringify({a:1}));
D
import { appendFileSync } from 'node:fs';
appendFileSync('output.json', JSON.stringify({a:1}));
appendFileSync('output.json', '\n');
Attempts:
2 left
💡 Hint
Appending JSON data as a string with a newline keeps entries separated.

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

  1. Step 1: Understand the meaning of appending

    Appending means adding data to the end of existing content without deleting it.
  2. Step 2: Compare with other file operations

    Replacing or deleting would remove old content, which is not appending.
  3. Final Answer:

    Adding new content to the end of the existing file without removing old content -> Option A
  4. 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

  1. Step 1: Identify the correct method for appending

    The method to add content at the end is 'appendFile' in 'fs/promises'.
  2. Step 2: Check the syntax

    Using 'await fs.appendFile(filename, data)' is the correct syntax.
  3. Final Answer:

    await fs.appendFile('file.txt', 'Hello World'); -> Option A
  4. 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"?
import { appendFile } from 'fs/promises';
await appendFile('log.txt', 'Entry1\n');
await appendFile('log.txt', 'Entry2');
medium
A. StartEntry1\nEntry2
B. Entry1\nEntry2
C. Start\nEntry1Entry2
D. Start\nEntry1\nEntry2

Solution

  1. Step 1: Understand initial file content

    The file starts with "Start\n", so it ends with a newline.
  2. Step 2: Analyze each append operation

    First append adds "Entry1\n" after existing content, second adds "Entry2" after that.
  3. Step 3: Combine all content

    Resulting content is "Start\nEntry1\nEntry2" exactly as appended.
  4. Final Answer:

    Start\nEntry1\nEntry2 -> Option D
  5. 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

  1. Step 1: Check usage of async function

    fs.appendFile returns a promise and should be awaited or handled.
  2. Step 2: Identify missing await

    Without await, appendFile runs asynchronously and may not finish before console.log.
  3. Final Answer:

    Missing await before fs.appendFile causing asynchronous issue -> Option C
  4. 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

  1. Step 1: Understand appending multiple entries

    Appending adds text exactly as given, so newlines must be included explicitly.
  2. Step 2: Choose method to add new lines

    Adding '\n' at the end of each entry ensures each appears on its own line.
  3. Step 3: Compare other options

    writeFile overwrites, appendFile without '\n' joins lines, readFile + writeFile is inefficient.
  4. Final Answer:

    Use appendFile with '\n' at the end of each entry string -> Option B
  5. Quick Check:

    Newline needed to separate appended lines [OK]
Hint: Add '\n' explicitly to each appended string [OK]
Common Mistakes:
  • Forgetting to add newline characters
  • Using writeFile which overwrites content
  • Assuming file system adds newlines automatically