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
Reading Files with Promises using fs.promises in Node.js
📖 Scenario: You are building a simple Node.js script to read the contents of a text file asynchronously. This is useful when you want your program to keep working without waiting for the file to finish loading.
🎯 Goal: Learn how to use fs.promises to read a file asynchronously and handle the content using promises.
📋 What You'll Learn
Create a variable to import the fs/promises module.
Create a variable with the exact filename example.txt.
Use fs.readFile to read the file content as a string.
Add a .then() method to handle the file content.
Add a .catch() method to handle any errors.
💡 Why This Matters
🌍 Real World
Reading files asynchronously is common in Node.js applications to avoid blocking the program while waiting for file operations. This helps keep apps responsive.
💼 Career
Understanding how to use promises with fs.promises is important for backend developers working with Node.js to handle file input/output efficiently.
Progress0 / 4 steps
1
Import fs.promises and set filename
Create a variable called fs that imports the fs/promises module using import. Then create a variable called filename and set it to the string 'example.txt'.
Node.js
Hint
Use import fs from 'fs/promises' to get the promises API of fs. Then assign filename to 'example.txt'.
2
Read the file content with readFile
Use fs.readFile with the variable filename and the option { encoding: 'utf8' } to read the file content as a string. Assign the returned promise to a variable called filePromise.
Node.js
Hint
Call fs.readFile(filename, { encoding: 'utf8' }) and assign it to filePromise.
3
Handle the file content with then
Add a .then() method to filePromise that takes a parameter called content and returns content. Assign this to a variable called contentPromise.
Node.js
Hint
Use filePromise.then(content => content) and assign it to contentPromise.
4
Add catch to handle errors
Add a .catch() method to contentPromise that takes a parameter called error and returns the string 'Error reading file'. Assign this to a variable called finalPromise.
Node.js
Hint
Use contentPromise.catch(error => 'Error reading file') and assign it to finalPromise.
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
Step 1: Understand fs.promises.readFile behavior
This method returns a promise that will resolve when the file is read successfully.
Step 2: Identify the return type
Since it returns a promise, you can use await or .then() to get the file content asynchronously.
Final Answer:
A promise that resolves with the file content -> Option B
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
Step 1: Use async/await with promises
To get the file content, you must await the promise returned by fs.promises.readFile.
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.
Final Answer:
const data = await fs.promises.readFile('file.txt'); -> Option A
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
Step 1: Understand readFile with encoding
When you pass 'utf8' as the second argument, the promise resolves with a string containing the file content.
Step 2: Check the logged type
The typeof operator on a string returns 'string', so the console logs 'string'.
Final Answer:
'string' -> Option C
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
Step 1: Check asynchronous call handling
The fs.readFile returns a promise, so to get the file content, you must await it.
Step 2: Identify the missing await
Without await, data is a promise object, so logging it shows a promise, not file content.
Final Answer:
Missing await before fs.readFile call -> Option A
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
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.
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.