Mastering the `fs.promises` Module in Node.js 🚀
SOVANNARO

SOVANNARO @sovannaro

About: Passionate developer specializing in JavaScript, TypeScript, React, Vue, and Angular. I thrive on solving problems and building innovative solutions that make a difference in the modern world.

Location:
Phnom Penh, Cambodia
Joined:
Dec 1, 2021

Mastering the `fs.promises` Module in Node.js 🚀

Publish Date: Mar 1
1 0

Hey there, awesome devs! 👋 Have you ever wanted to read, write, or manage files in Node.js without the complexity of callbacks? Well, you're in luck because the fs.promises module makes working with files cleaner and easier using Promises and async/await. 💡


📂 What is fs.promises?

The fs (File System) module in Node.js allows us to interact with the file system, such as reading and writing files. Traditionally, fs methods use callbacks, which can lead to messy, hard-to-read code. 🤯

To solve this, Node.js introduced fs.promises, which provides a Promise-based API for file operations. This means we can now use async/await for much cleaner and more readable code! 🎉


🔥 Getting Started

To use fs.promises, simply import it like this:

const fs = require('fs').promises;
Enter fullscreen mode Exit fullscreen mode

Now, let’s explore some common file operations! 🚀


📖 Reading a File

Let’s read a file asynchronously using fs.promises.readFile:

const fs = require('fs').promises;

async function readFile() {
    try {
        const data = await fs.readFile('example.txt', 'utf-8');
        console.log('File content:', data);
    } catch (error) {
        console.error('Error reading file:', error);
    }
}

readFile();
Enter fullscreen mode Exit fullscreen mode

No callbacks! Just simple and clean async/await.


✍️ Writing to a File

Want to write some text to a file? Use fs.promises.writeFile:

const fs = require('fs').promises;

async function writeFile() {
    try {
        await fs.writeFile('example.txt', 'Hello, Node.js!');
        console.log('File written successfully!');
    } catch (error) {
        console.error('Error writing file:', error);
    }
}

writeFile();
Enter fullscreen mode Exit fullscreen mode

✅ No more callback hell! 🚀


🔄 Appending to a File

Want to add data instead of overwriting? Use fs.promises.appendFile:

async function appendToFile() {
    try {
        await fs.appendFile('example.txt', '\nThis is new content!');
        console.log('Content appended successfully!');
    } catch (error) {
        console.error('Error appending file:', error);
    }
}

appendToFile();
Enter fullscreen mode Exit fullscreen mode

✅ This adds text without replacing existing content. 📄


🗑️ Deleting a File

Need to remove a file? Use fs.promises.unlink:

async function deleteFile() {
    try {
        await fs.unlink('example.txt');
        console.log('File deleted successfully!');
    } catch (error) {
        console.error('Error deleting file:', error);
    }
}

deleteFile();
Enter fullscreen mode Exit fullscreen mode

✅ Quick and easy file deletion! 🗑️


📁 Creating and Removing Directories

📌 Creating a Directory

async function createDir() {
    try {
        await fs.mkdir('new-folder');
        console.log('Directory created!');
    } catch (error) {
        console.error('Error creating directory:', error);
    }
}

createDir();
Enter fullscreen mode Exit fullscreen mode

🗑️ Removing a Directory

async function removeDir() {
    try {
        await fs.rmdir('new-folder');
        console.log('Directory removed!');
    } catch (error) {
        console.error('Error removing directory:', error);
    }
}

removeDir();
Enter fullscreen mode Exit fullscreen mode

✅ Managing directories is just as easy as files! 📂


🚀 Why Use fs.promises?

  • Cleaner Code: No more messy callback nesting. 🎯
  • Better Readability: async/await makes it easy to follow. 👀
  • Error Handling: try/catch blocks handle errors gracefully. 🛡️
  • Performance: Asynchronous operations keep the event loop non-blocking. ⚡

🔥 Final Thoughts

Using fs.promises makes working with files in Node.js simple, clean, and enjoyable. 🚀

In the next article, we’ll explore Streams – stay tuned! 🎯

If you found this blog helpful, make sure to follow me on GitHub 👉 github.com/sovannaro and drop a ⭐. Your support keeps me motivated to create more awesome content! 😍

Happy coding! 💻🔥

Comments 0 total

    Add comment