how to delete everything from a folder in js

How to delete everything from a folder in JS

If you need to delete everything from a folder in JS, you can use the built-in Node.js module called "fs" (File System).

The easiest way to delete everything from a folder is to use the "fs.unlink()" method. This method removes a file or symbolic link.


    const fs = require('fs');
    const path = './folder_name/';

    fs.readdirSync(path).forEach((file) => {
      fs.unlinkSync(path + file);
    });
  

This code reads the names of all files in the "folder_name" directory and uses the "fs.unlinkSync()" method to delete each file.

Method 2: Using fs.rmdir()

If you need to delete all files and subdirectories from a folder, you can use the "fs.rmdir()" method. This method removes a directory.


    const fs = require('fs');
    const path = './folder_name/';

    fs.readdirSync(path).forEach((file) => {
      if (fs.statSync(path + file).isDirectory()) {
        fs.rmdirSync(path + file, { recursive: true });
      } else {
        fs.unlinkSync(path + file);
      }
    });
  

This code reads the names of all files and subdirectories in the "folder_name" directory and uses the "fs.rmdirSync()" method to delete each subdirectory and the "fs.unlinkSync()" method to delete each file.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe