,

Node js: How to delete all files from a directory without removing the directory itself

Posted by

<!DOCTYPE html>

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

When working with Node.js, you may come across a situation where you need to remove all files from a directory without actually removing the directory itself. This can be done easily using the built-in fs module in Node.js.

Here is a step-by-step guide on how to achieve this:

  1. First, require the fs module in your Node.js application:
  2. const fs = require('fs');

  3. Next, use the fs.readdir method to read all the files in the directory:
  4. fs.readdir(directoryPath, (err, files) => {

  5. Then, loop through all the files and use the fs.unlink method to remove each file:
  6. files.forEach(file => {
    fs.unlink(`${directoryPath}/${file}`, err => {
    if (err) throw err;
    });
    });

  7. Finally, you can console log a message to indicate that all the files have been removed:
  8. console.log('All files have been removed from the directory.');

  9. Don’t forget to handle any errors that may occur during the process:
  10. if (err) throw err;

And that’s it! You have successfully removed all files from a directory without removing the directory itself in Node.js.

Happy coding!