How to remove all files from directory without removing directory in Node.js

To remove all files from a directory, first you need to list all files in the directory using fs.readdir, then you can use fs.unlink to remove each file. Also fs.readdir will give just the file names, you need to concat with the directory name to get the full path. If your folder have other folders inside, you will need to check for it and use fs.rmdir instead.

Here is an example

const fs = require("fs");
const path = require("path");

const directory = "test";

fs.readdir(directory, (err, files) => {
  if (err) throw err;

  for (const file of files) {
    fs.unlink(path.join(directory, file), (err) => {
      if (err) throw err;
    });
  }
});

Using promises

import fs from "node:fs/promises";
import path from "node:path";

const directory = "test";

for (const file of await fs.readdir(directory)) {
  await fs.unlink(path.join(directory, file));
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)