How to use fs promises in Node.js

Using fs.promises provides cleaner, more readable code for file system operations compared to callback-based methods, especially when handling multiple sequential file operations. As the creator of CoreUI, a widely used open-source UI library, I’ve modernized countless file processing scripts using fs.promises over 25 years of development. From my expertise, the most effective approach is using fs.promises with async/await syntax for synchronous-looking asynchronous file operations. This eliminates callback hell and makes error handling more intuitive.

Use fs.promises with async/await for cleaner asynchronous file operations.

const fs = require('fs').promises

async function processFile() {
  try {
    const data = await fs.readFile('input.txt', 'utf8')
    const processed = data.toUpperCase()
    await fs.writeFile('output.txt', processed)
    console.log('File processed successfully')
  } catch (error) {
    console.error('Error processing file:', error)
  }
}

Here fs.promises provides promise-based versions of all file system methods. The async/await syntax makes the code read like synchronous operations while maintaining asynchronous execution. Error handling is simplified with try/catch blocks instead of checking error parameters in callbacks.

Best Practice Note:

This is the same promise-based file handling approach we use in CoreUI build scripts for better maintainability. Always wrap fs.promises operations in try/catch blocks and consider using Promise.all() for concurrent file operations to improve performance.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author