fs/promises API
Overview
The File System (fs) module is how Node interacts with the server's hard drive. Historically, it relied entirely on 'Callbacks', leading to deep, unreadable 'Callback Hell' (Pyramid of Doom). Modern Node.js provides a native fs/promises module. It contains all the standard Non-Blocking file operations, but wrapped in native Promises, allowing you to use hyper-clean async/await syntax for reading, writing, and deleting files.
Syntax
// IMPORT THE PROMISE VERSION OF FS!
const fs = require('fs/promises');
async function manageFiles() {
try {
// 1. Write to a file (Creates it if it doesn't exist, OVERWRITES if it does)
await fs.writeFile('log.txt', 'System booted up.\n');
// 2. Append to a file (Adds to the end without deleting old data)
await fs.appendFile('log.txt', 'User logged in.\n');
// 3. Read a file
// MUST specify 'utf8' encoding, otherwise it returns a raw Binary Buffer!
const data = await fs.readFile('log.txt', 'utf8');
console.log(data);
// 4. Delete a file safely
await fs.unlink('old_temp_file.txt');
} catch (error) {
console.error("A file operation failed:", error);
}
}
manageFiles();Common Pitfalls
- Forgetting the
utf8encoding argument inreadFile. Hard drives do not store English words; they store raw bytes. If you don't tellreadFileto decode the bytes into UTF-8 text, it will return aBufferobject (e.g.,<Buffer 53 79 73 74 65 ...>). If you try to print or send that Buffer in an API, it will look like gibberish. - Using
fs.writeFilewhen you meantfs.appendFile.writeFileis extremely destructive. It instantly truncates (deletes) the entire contents of the existing file before writing the new string.
Interview Questions
await fs.readFile()?Absolutely not. readFile attempts to load the entire file into the server's RAM at once. If the file is 10GB, and your server only has 2GB of RAM, V8 will throw a fatal ERR_STRING_TOO_LONG and crash the server instantly. You MUST use Streams (fs.createReadStream) for large files.
Real-World Example
Using fs/promises to check if a file exists before trying to read it.
const fs = require('fs/promises');
async function safeRead() {
try {
// access() throws a rejected promise if the file doesn't exist
await fs.access('critical_data.json');
// If we get here, it's safe to read!
const raw = await fs.readFile('critical_data.json', 'utf8');
return JSON.parse(raw);
} catch (error) {
// File doesn't exist, return a safe default!
return { status: "Empty" };
}
}Check Your Knowledge
Test your understanding of fs/promises API with these quick questions.