Skip to content

How to remove files in the folder using Node.js

In this post, I will show you how to remove files in the folder using Node.js.

Using fs module

The fs module provides a way to interact with the file system in a way modeled on standard POSIX functions.

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

async function removeAllFilesInFolder(folderPath) {
  try {
    const files = await fs.readdir(folderPath);
    
    for (const file of files) {
      const filePath = path.join(folderPath, file);
      const stats = await fs.stat(filePath);
      
      if (stats.isFile()) {
        await fs.unlink(filePath); // Remove the file
      } else if (stats.isDirectory()) {
        await removeAllFilesInFolder(filePath); // Recursively remove files in subdirectories
        await fs.rmdir(filePath); // Remove the empty subdirectory
      }
    }
    
    console.log('All files have been removed');
  } catch (err) {
    console.error('Error while removing files:', err);
  }
}

// Usage example
const folderPath = './path/to/folder';
removeAllFilesInFolder(folderPath);

In the above code snippet, we are using the fs module to read the files in the folder and then remove them one by one using the fs.unlink method.