How to use fs promises in Node.js

Using fs promises in Node.js provides modern asynchronous file system operations with async/await syntax, eliminating callback hell and enabling cleaner error handling patterns. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented fs promises in countless Node.js applications for file processing, build systems, and content management with much cleaner and more maintainable code. From my expertise, the most effective approach is importing fs promises and using async/await with proper try/catch error handling. This method provides modern asynchronous file operations with clean syntax and comprehensive error management.

Import fs promises and use async/await syntax for modern file system operations with clean error handling.

// Import fs promises
import { readFile, writeFile, readdir, mkdir, stat, access } from 'fs/promises'
import { constants } from 'fs'

// Read file with promises
async function readFileExample() {
  try {
    const data = await readFile('config.json', 'utf8')
    const config = JSON.parse(data)
    console.log('Config loaded:', config)
    return config
  } catch (error) {
    console.error('Error reading file:', error.message)
    return null
  }
}

// Write file with promises
async function writeFileExample(data) {
  try {
    const jsonData = JSON.stringify(data, null, 2)
    await writeFile('output.json', jsonData, 'utf8')
    console.log('File written successfully')
  } catch (error) {
    console.error('Error writing file:', error.message)
  }
}

// Multiple file operations
async function processFiles() {
  try {
    // Check if directory exists
    await access('./data', constants.F_OK)

    // Read directory contents
    const files = await readdir('./data')
    console.log('Files found:', files)

    // Process each file
    const results = []
    for (const file of files) {
      if (file.endsWith('.json')) {
        const content = await readFile(`./data/${file}`, 'utf8')
        const data = JSON.parse(content)
        results.push({ file, data })
      }
    }

    // Write combined results
    await writeFile('combined.json', JSON.stringify(results, null, 2))
    console.log('Processing complete')

  } catch (error) {
    if (error.code === 'ENOENT') {
      console.log('Data directory does not exist, creating...')
      await mkdir('./data', { recursive: true })
    } else {
      console.error('Error processing files:', error.message)
    }
  }
}

// File system utilities with promises
async function fileSystemUtils() {
  try {
    // Get file stats
    const stats = await stat('package.json')
    console.log('File size:', stats.size)
    console.log('Is file:', stats.isFile())
    console.log('Modified:', stats.mtime)

    // Check file accessibility
    await access('package.json', constants.R_OK | constants.W_OK)
    console.log('File is readable and writable')

    // Create nested directories
    await mkdir('./src/components/ui', { recursive: true })
    console.log('Nested directories created')

  } catch (error) {
    console.error('File system operation failed:', error.message)
  }
}

// Parallel file operations
async function parallelOperations() {
  try {
    const [file1, file2, file3] = await Promise.all([
      readFile('file1.txt', 'utf8'),
      readFile('file2.txt', 'utf8'),
      readFile('file3.txt', 'utf8')
    ])

    console.log('All files read successfully')
    return { file1, file2, file3 }

  } catch (error) {
    console.error('Error reading files in parallel:', error.message)
  }
}

The fs/promises module provides promise-based versions of all file system methods. Use async/await for clean asynchronous code and try/catch for error handling. Import specific methods for better tree-shaking and performance. Handle common error codes like ENOENT (file not found) appropriately for robust applications.

Best Practice Note:

This is the same fs promises approach we use in CoreUI Node.js build tools for clean asynchronous file processing and maintainable build scripts.


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