Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to remove all files from directory without removing directory in Node.js.

In this article, we’ll look at how to remove all files from directory without removing directory in Node.js.

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

To remove all files from directory without removing directory in Node.js, we can use fs.readdir to read the file paths from a directory.

And then we use fs.unlink to delete each file with each path.

For instance, we write

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;
    });
  }
});

to call readdir with directory to read the file paths in directory.

Then we loop through the files paths in the callback to delete all the listed files.

In the loop, we call fs.unlink with the full path returned by path.join(directory, file) to delete the file.

Conclusion

To remove all files from directory without removing directory in Node.js, we can use fs.readdir to read the file paths from a directory.

And then we use fs.unlink to delete each file with each path.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *