Skip to content
the poor coder

how to delete everything from a folder in js

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

    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.

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC