How to delete files in Node.js

Deleting files in Node.js enables cleanup operations, temporary file management, and file system maintenance through the built-in filesystem module methods. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented file deletion in countless Node.js applications for cleanup scripts, temporary file management, and data processing workflows. From my expertise, the most effective approach is using fs.unlink() with proper error handling and file existence validation. This method provides safe file deletion with comprehensive error management and validation checks.

Use fs.unlink() to permanently remove files from the filesystem with proper error handling.

import { unlink, access } from 'fs/promises'
import { constants } from 'fs'

// Simple file deletion
async function deleteFile(filePath) {
  try {
    await unlink(filePath)
    console.log('File deleted successfully')
  } catch (error) {
    console.error('Delete failed:', error.message)
  }
}

// Delete with existence check
async function safeDeleteFile(filePath) {
  try {
    await access(filePath, constants.F_OK)
    await unlink(filePath)
    console.log(`${filePath} deleted successfully`)
  } catch (error) {
    if (error.code === 'ENOENT') {
      console.log('File does not exist')
    } else {
      console.error('Delete failed:', error.message)
    }
  }
}

// Batch file deletion
async function deleteMultipleFiles(filePaths) {
  const results = await Promise.allSettled(
    filePaths.map(path => unlink(path))
  )

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`${filePaths[index]} deleted`)
    } else {
      console.error(`Failed to delete ${filePaths[index]}`)
    }
  })
}

The fs.unlink() method permanently removes files from the filesystem. Use fs.access() to check file existence before deletion. Handle ENOENT errors gracefully when files don’t exist. Use Promise.allSettled() for batch operations to handle partial failures.

Best Practice Note:

This is the same file deletion approach we use in CoreUI Node.js applications for cleanup operations and temporary file management.


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

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team