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 the readdir method to get an array of file paths in the directory.

Then we can use unlink to remove all the files.

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 to get an array of files.

Then we loop through the files in the for-of loop.

In the loop body, we call fs.unlink with the path of each file returned by path.join to remove them.

Conclusion

To remove all files from directory without removing directory in Node.js, we can use the readdir method to get an array of file paths in the directory.

Then we can use unlink to remove all the files.

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 *