Reading files with promises lets you get file content without blocking your program. It helps keep your app fast and smooth.
Reading files with promises (fs.promises) in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
import { promises as fs } from 'fs'; async function readFileExample() { try { const data = await fs.readFile('filename.txt', 'utf8'); console.log(data); } catch (error) { console.error('Error reading file:', error); } }
Use fs.readFile from fs.promises to get a promise that resolves with file content.
Always use try/catch or .catch() to handle errors when reading files.
Examples
.then() and .catch() to handle the promise from reading a file.Node.js
import { promises as fs } from 'fs'; fs.readFile('example.txt', 'utf8') .then(data => console.log(data)) .catch(err => console.error(err));
async/await for cleaner, easier-to-read code.Node.js
import { promises as fs } from 'fs'; async function read() { const content = await fs.readFile('example.txt', 'utf8'); console.log(content); } read();
Node.js
import { promises as fs } from 'fs'; async function readFile() { try { const data = await fs.readFile('missing.txt', 'utf8'); console.log(data); } catch (error) { console.error('File not found or error:', error.message); } } readFile();
Sample Program
This program reads the file greeting.txt and prints its content. If the file is missing or unreadable, it shows an error message.
Node.js
import { promises as fs } from 'fs'; async function showFileContent() { try { const content = await fs.readFile('greeting.txt', 'utf8'); console.log('File content:'); console.log(content); } catch (error) { console.error('Failed to read file:', error.message); } } showFileContent();
Important Notes
Always specify the encoding like 'utf8' to get a string instead of a buffer.
Promises let you write asynchronous code that looks like normal, step-by-step code.
Use Node.js DevTools or console logs to check if your file path is correct.
Summary
Use fs.promises.readFile to read files asynchronously with promises.
Handle errors with try/catch or .catch() to avoid crashes.
Use async/await for clean and readable asynchronous code.
Practice
1. What does
fs.promises.readFile return when reading a file in Node.js?easy
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 useawaitor.then()to get the file content asynchronously.Final Answer:
A promise that resolves with the file content -> Option BQuick 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
Solution
Step 1: Use async/await with promises
To get the file content, you must await the promise returned byfs.promises.readFile.Step 2: Check syntax correctness
const data = await fs.promises.readFile('file.txt'); correctly usesawaitwithfs.promises.readFile. const data = fs.promises.readFile('file.txt'); missesawait, 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 AQuick 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
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
Thetypeofoperator on a string returns 'string', so the console logs 'string'.Final Answer:
'string' -> Option CQuick 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
Solution
Step 1: Check asynchronous call handling
Thefs.readFilereturns a promise, so to get the file content, you must await it.Step 2: Identify the missing await
Withoutawait,datais a promise object, so logging it shows a promise, not file content.Final Answer:
Missing await before fs.readFile call -> Option AQuick 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
Solution
Step 1: Understand concurrent reading with Promise.all
To read multiple files concurrently, map each filename to a promise and usePromise.allto 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.Final Answer:
const contents = await Promise.all(files.map(f => fs.readFile(f, 'utf8'))); -> Option DQuick 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
