Bird
Raised Fist0
Node.jsframework~20 mins

Writing 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 Writing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Node.js file write operation?
Consider this Node.js code snippet that writes to a file asynchronously. What will be logged to the console?
Node.js
import { writeFile } from 'node:fs/promises';

async function writeData() {
  try {
    await writeFile('test.txt', 'Hello World');
    console.log('Write successful');
  } catch (err) {
    console.log('Write failed');
  }
}

writeData();
ASyntaxError
BWrite failed
CNo output
DWrite successful
Attempts:
2 left
💡 Hint
The writeFile function from 'fs/promises' returns a promise that resolves on success.
component_behavior
intermediate
2:00remaining
What happens if you try to write to a file without permissions?
Given this Node.js code snippet, what will be the console output if the process lacks write permission to 'readonly.txt'?
Node.js
import { writeFile } from 'node:fs/promises';

async function writeData() {
  try {
    await writeFile('readonly.txt', 'Data');
    console.log('Write successful');
  } catch (err) {
    console.log(err.code);
  }
}

writeData();
AEACCES
BSyntaxError
CENOENT
DWrite successful
Attempts:
2 left
💡 Hint
EACCES is the error code for permission denied in Node.js.
📝 Syntax
advanced
2:00remaining
Which option correctly appends text to a file asynchronously?
Select the code snippet that appends 'More data' to 'log.txt' using Node.js fs/promises module.
A
import { writeFile } from 'node:fs/promises';
await writeFile('log.txt', 'More data', { flag: 'a' });
B
import { appendFile } from 'node:fs/promises';
await appendFile('log.txt', 'More data');
C
import { writeFile } from 'node:fs';
writeFile('log.txt', 'More data', { flag: 'a' });
D
import { appendFileSync } from 'node:fs/promises';
await appendFileSync('log.txt', 'More data');
Attempts:
2 left
💡 Hint
Appending can be done by writeFile with flag 'a' or appendFile function.
🔧 Debug
advanced
2:00remaining
Why does this code throw an error when writing a file?
Identify the cause of the error in this Node.js code snippet:
Node.js
import fs from 'fs/promises';

fs.writeFile('output.txt', 'Hello').then(() => {
  console.log('Done');
});

fs.writeFile('output.txt', 'World');
AwriteFile requires a callback function, missing here.
Bfs module import is incorrect, should be 'node:fs/promises'.
CSecond writeFile call is missing await or then, causing unhandled promise rejection.
DCannot call writeFile twice on the same file.
Attempts:
2 left
💡 Hint
Promises must be handled to avoid unhandled rejections.
🧠 Conceptual
expert
2:00remaining
What is the effect of using the 'wx' flag in writeFile options?
In Node.js fs/promises writeFile, what happens if you use the option { flag: 'wx' } when writing to a file?
AThe write operation is performed with exclusive lock preventing other writes.
BThe file is created and written only if it does not already exist; otherwise, an error is thrown.
CThe file is appended to if it exists; otherwise, it is created.
DThe file is overwritten regardless of existing content.
Attempts:
2 left
💡 Hint
The 'x' flag means exclusive creation in file system flags.

Practice

(1/5)
1. What is the main purpose of using the fs/promises module in Node.js when writing files?
easy
A. To write files using promises and async/await for cleaner code
B. To read files synchronously
C. To create HTTP servers
D. To manage environment variables

Solution

  1. Step 1: Understand the role of fs/promises

    The fs/promises module provides promise-based versions of file system functions, allowing use of async/await.
  2. Step 2: Identify the purpose related to writing files

    It is mainly used to write files asynchronously with cleaner syntax compared to callbacks.
  3. Final Answer:

    To write files using promises and async/await for cleaner code -> Option A
  4. Quick Check:

    fs/promises = async file writing [OK]
Hint: Remember fs/promises is for async file operations [OK]
Common Mistakes:
  • Confusing fs/promises with synchronous fs methods
  • Thinking fs/promises is for reading environment variables
  • Assuming fs/promises creates servers
2. Which of the following is the correct syntax to write 'Hello World' to a file named 'greet.txt' using fs/promises in Node.js?
easy
A. fs.writeFileSync('greet.txt', 'Hello World');
B. fs.promises.write('greet.txt', 'Hello World');
C. await fs.writeFile('greet.txt', 'Hello World');
D. await fs.write('greet.txt', 'Hello World');

Solution

  1. Step 1: Recall the correct method name in fs/promises

    The method to write files is writeFile, used with await for promises.
  2. Step 2: Check syntax correctness

    await fs.writeFile('greet.txt', 'Hello World'); uses await fs.writeFile('greet.txt', 'Hello World'); which is correct syntax for async write.
  3. Final Answer:

    await fs.writeFile('greet.txt', 'Hello World'); -> Option C
  4. Quick Check:

    writeFile + await = correct syntax [OK]
Hint: Use await with fs.writeFile for async writing [OK]
Common Mistakes:
  • Using writeFileSync without await in async code
  • Calling non-existent fs.promises.write method
  • Omitting await with promise-based methods
3. What will be the output of the following code snippet?
import { writeFile } from 'fs/promises';

async function save() {
  await writeFile('data.txt', 'Node.js Rocks!');
  console.log('File saved');
}
save();
medium
A. No output
B. File saved
C. File saved\nNode.js Rocks!
D. SyntaxError

Solution

  1. Step 1: Analyze the async function behavior

    The function writes 'Node.js Rocks!' to 'data.txt' asynchronously, then logs 'File saved'.
  2. Step 2: Determine console output

    Since writeFile completes before console.log, the output is 'File saved' printed once.
  3. Final Answer:

    File saved -> Option B
  4. Quick Check:

    Async write then log = 'File saved' [OK]
Hint: Async writeFile logs after completion [OK]
Common Mistakes:
  • Expecting file content to print to console
  • Confusing syntax error with valid import
  • Thinking no output occurs without explicit return
4. Identify the error in the following code that attempts to write to a file:
import fs from 'fs/promises';

async function writeData() {
  fs.writeFile('output.txt', 'Test data');
  console.log('Done');
}
writeData();
medium
A. writeFile method does not exist in fs/promises
B. Incorrect import statement for fs/promises
C. File path 'output.txt' is invalid
D. Missing await before fs.writeFile causing unhandled promise

Solution

  1. Step 1: Check async function usage

    The function calls fs.writeFile but does not await it, so the promise is not handled properly.
  2. Step 2: Understand consequences of missing await

    Without await, the write operation may not complete before 'Done' logs, and errors won't be caught.
  3. Final Answer:

    Missing await before fs.writeFile causing unhandled promise -> Option D
  4. Quick Check:

    Always await async fs methods [OK]
Hint: Always await async file writes to avoid errors [OK]
Common Mistakes:
  • Forgetting await with async fs methods
  • Assuming import syntax is wrong when it is correct
  • Blaming file path without checking code first
5. You want to write multiple lines to a file 'log.txt' asynchronously, appending each new line without overwriting. Which approach correctly achieves this using fs/promises?
hard
A. Use await fs.appendFile('log.txt', 'New line\n'); inside an async function
B. Use await fs.writeFile('log.txt', 'New line\n'); repeatedly
C. Use fs.writeFileSync('log.txt', 'New line\n'); inside async function
D. Use fs.appendFileSync('log.txt', 'New line\n'); without async

Solution

  1. Step 1: Understand file appending vs overwriting

    To add lines without erasing existing content, appending is needed, not writeFile which overwrites.
  2. Step 2: Choose correct async method

    fs.appendFile from fs/promises appends asynchronously and works with await.
  3. Final Answer:

    Use await fs.appendFile('log.txt', 'New line\n'); inside an async function -> Option A
  4. Quick Check:

    appendFile + await = append lines safely [OK]
Hint: Use appendFile to add lines without erasing [OK]
Common Mistakes:
  • Using writeFile which overwrites file content
  • Using synchronous methods in async code
  • Not adding newline characters when appending