Topic 35 of 55
File (fs) Promises API
Overview
The `fs/promises` module provides the same asynchronous, non-blocking file operations, but returns Promises instead of using callbacks. This allows you to use modern `async/await` syntax, resulting in much cleaner, flatter code.
Syntax
javascript
// Import the promises version of the fs module
const fs = require('fs/promises');
async function processFile() {
try {
// Execution pauses here until the file is read,
// BUT the Node event loop is NOT blocked! Other users can still be served.
const data = await fs.readFile('./data.txt', 'utf8');
console.log("File content:", data);
await fs.writeFile('./copy.txt', data);
console.log("File copied successfully");
} catch (err) {
console.error("An error occurred:", err);
}
}
processFile();Common Pitfalls
- Forgetting to `await` an `fs/promises` method is a very common bug. If you write `fs.writeFile(...)` without `await`, the function will return instantly and errors may be swallowed.
- If you are reading a massively huge file (gigabytes), `fs.readFile` will load the entire thing into RAM and crash your server. Use Streams (`fs.createReadStream`) for large files.
Real-World Example
Reading a directory and deleting all files inside it concurrently using Promise.all:
example
javascript
const fs = require('fs/promises');
const path = require('path');
async function clearTempDirectory() {
const tempDir = './temp';
try {
// 1. Get an array of filenames
const files = await fs.readdir(tempDir);
// 2. Create an array of Promises (one for each file deletion)
const deletePromises = files.map(file => {
const fullPath = path.join(tempDir, file);
return fs.unlink(fullPath); // unlink deletes a file
});
// 3. Wait for ALL deletions to finish concurrently
await Promise.all(deletePromises);
console.log(`Successfully deleted ${files.length} files.`);
} catch (err) {
console.error("Cleanup failed:", err);
}
}