Bird
Raised Fist0
Node.jsframework~20 mins

Reading files with promises (fs.promises) 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 Reading 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 code reading a file?
Consider this Node.js code using fs.promises to read a file named 'example.txt'. What will be logged to the console?
Node.js
import { promises as fs } from 'fs';

async function readFile() {
  try {
    const data = await fs.readFile('example.txt', 'utf8');
    console.log(data.trim());
  } catch (error) {
    console.log('Error:', error.message);
  }
}

readFile();
ASyntaxError due to missing callback in readFile
BThe trimmed content of 'example.txt' is printed.
Cundefined
DError: ENOENT: no such file or directory, open 'example.txt'
Attempts:
2 left
💡 Hint
Check how fs.promises.readFile returns a promise and how await handles it.
component_behavior
intermediate
2:00remaining
What happens if you forget to await fs.promises.readFile?
In this code snippet, what will be logged to the console?
Node.js
import { promises as fs } from 'fs';

async function readFile() {
  try {
    const data = fs.readFile('example.txt', 'utf8');
    console.log(typeof data);
  } catch (error) {
    console.log('Error:', error.message);
  }
}

readFile();
ASyntaxError due to missing await keyword
B'string' is logged because readFile returns file content directly.
CError: Cannot read property 'trim' of undefined
D'object' is logged because data is a Promise object.
Attempts:
2 left
💡 Hint
Remember what fs.promises.readFile returns when not awaited.
📝 Syntax
advanced
2:00remaining
Which option correctly reads a file using fs.promises with async/await?
Select the code snippet that correctly reads 'data.txt' and logs its content.
A
const fs = require('fs').promises;
async function read() {
  const content = await fs.readFile('data.txt', 'utf8');
  console.log(content);
}
read();
B
import fs from 'fs';
async function read() {
  const content = await fs.promises.readFile('data.txt');
  console.log(content.toString());
}
read();
C
import { promises as fs } from 'fs';
async function read() {
  const content = await fs.readFile('data.txt', 'utf8');
  console.log(content);
}
read();
D
import fs from 'fs/promises';
function read() {
  const content = fs.readFileSync('data.txt', 'utf8');
  console.log(content);
}
read();
Attempts:
2 left
💡 Hint
Check the import style and usage of async/await with fs.promises.
🔧 Debug
advanced
2:00remaining
Why does this code throw an error when reading a file?
This code throws an error. What is the cause?
Node.js
import { promises as fs } from 'fs';

async function read() {
  const data = await fs.readFile('missing.txt');
  console.log(data);
}

read();
AThe file 'missing.txt' does not exist, causing a rejection that is not caught.
Bawait cannot be used outside a try/catch block.
CMissing encoding argument causes a SyntaxError.
Dfs.readFile returns undefined without encoding.
Attempts:
2 left
💡 Hint
What happens if you try to read a file that does not exist without error handling?
🧠 Conceptual
expert
2:00remaining
What is the advantage of using fs.promises over callback-based fs methods?
Choose the best explanation for why developers prefer fs.promises for reading files.
Afs.promises allows using async/await syntax, making asynchronous code easier to read and maintain.
Bfs.promises automatically retries reading files on failure without extra code.
Cfs.promises reads files synchronously, improving performance.
Dfs.promises requires less memory because it streams files by default.
Attempts:
2 left
💡 Hint
Think about how promises improve asynchronous code structure.

Practice

(1/5)
1. What does fs.promises.readFile return when reading a file in Node.js?
easy
A. The file content directly as a string
B. A promise that resolves with the file content
C. A callback function to handle the file content
D. An event emitter for file reading progress

Solution

  1. Step 1: Understand fs.promises.readFile behavior

    This method returns a promise that will resolve when the file is read successfully.
  2. Step 2: Identify the return type

    Since it returns a promise, you can use await or .then() to get the file content asynchronously.
  3. Final Answer:

    A promise that resolves with the file content -> Option B
  4. Quick Check:

    fs.promises.readFile returns a promise [OK]
Hint: Remember: fs.promises methods always return promises [OK]
Common Mistakes:
  • Thinking it returns file content directly
  • Confusing with callback-based fs.readFile
  • Expecting an event emitter
2. Which of the following is the correct syntax to read a file using fs.promises.readFile with async/await?
easy
A. const data = await fs.promises.readFile('file.txt');
B. const data = fs.promises.readFile('file.txt');
C. fs.promises.readFile('file.txt', (err, data) => {});
D. await fs.readFile('file.txt', 'utf8');

Solution

  1. Step 1: Use async/await with promises

    To get the file content, you must await the promise returned by fs.promises.readFile.
  2. Step 2: Check syntax correctness

    const data = await fs.promises.readFile('file.txt'); correctly uses await with fs.promises.readFile. const data = fs.promises.readFile('file.txt'); misses await, C uses callback style which is incorrect here, and D uses wrong module method.
  3. Final Answer:

    const data = await fs.promises.readFile('file.txt'); -> Option A
  4. Quick Check:

    Use await with fs.promises.readFile [OK]
Hint: Always await promises to get their resolved value [OK]
Common Mistakes:
  • Omitting await and expecting immediate data
  • Using callback style with promises API
  • Mixing fs and fs.promises methods
3. What will be logged by this code snippet?
import { promises as fs } from 'fs';

async function read() {
  const content = await fs.readFile('example.txt', 'utf8');
  console.log(typeof content);
}

read();
medium
A. 'undefined'
B. 'object'
C. 'string'
D. Throws an error

Solution

  1. Step 1: Understand readFile with encoding

    When you pass 'utf8' as the second argument, the promise resolves with a string containing the file content.
  2. Step 2: Check the logged type

    The typeof operator on a string returns 'string', so the console logs 'string'.
  3. Final Answer:

    'string' -> Option C
  4. Quick Check:

    readFile with 'utf8' returns string [OK]
Hint: Add 'utf8' to get string, else Buffer is returned [OK]
Common Mistakes:
  • Forgetting encoding returns Buffer, not string
  • Expecting 'object' type for file content
  • Not awaiting the promise before logging
4. Identify the error in this code snippet:
import { promises as fs } from 'fs';

async function readFile() {
  const data = fs.readFile('data.txt', 'utf8');
  console.log(data);
}

readFile();
medium
A. Missing await before fs.readFile call
B. Wrong import syntax for fs.promises
C. readFile does not exist in fs.promises
D. Encoding 'utf8' is invalid here

Solution

  1. Step 1: Check asynchronous call handling

    The fs.readFile returns a promise, so to get the file content, you must await it.
  2. Step 2: Identify the missing await

    Without await, data is a promise object, so logging it shows a promise, not file content.
  3. Final Answer:

    Missing await before fs.readFile call -> Option A
  4. Quick Check:

    Always await promises to get resolved value [OK]
Hint: Await promises before using their results [OK]
Common Mistakes:
  • Logging promise instead of awaited result
  • Confusing import syntax for fs.promises
  • Passing wrong encoding string
5. You want to read multiple files ['a.txt', 'b.txt', 'c.txt'] concurrently using fs.promises.readFile and get their contents as strings. Which code snippet correctly does this?
hard
A. const contents = await fs.readFile(files, 'utf8');
B. const contents = files.map(f => await fs.readFile(f, 'utf8'));
C. const contents = files.forEach(async f => await fs.readFile(f, 'utf8'));
D. const contents = await Promise.all(files.map(f => fs.readFile(f, 'utf8')));

Solution

  1. Step 1: Understand concurrent reading with Promise.all

    To read multiple files concurrently, map each filename to a promise and use Promise.all to await all results.
  2. Step 2: Analyze each option

    const contents = await Promise.all(files.map(f => fs.readFile(f, 'utf8'))); correctly maps files to promises and awaits them all. const contents = files.map(f => await fs.readFile(f, 'utf8')); uses await inside map callback which is invalid syntax. const contents = files.forEach(async f => await fs.readFile(f, 'utf8')); uses forEach which returns undefined. const contents = await fs.readFile(files, 'utf8'); tries to read multiple files at once, which is invalid.
  3. Final Answer:

    const contents = await Promise.all(files.map(f => fs.readFile(f, 'utf8'))); -> Option D
  4. Quick Check:

    Use Promise.all with map for concurrent reads [OK]
Hint: Use Promise.all with map to await multiple promises [OK]
Common Mistakes:
  • Using await inside map callback directly
  • Using forEach which returns undefined
  • Trying to read multiple files in one readFile call