2

I wanted to delete multiple files which are ending with .pdf under the current directory. Suppose I have 3 different pdf files, 1 image file, and one text file, so in these, I want to delete those 3 different pdf files only.

What I have tried.

1st method fs.unlinkSync('./'+*+pdfname); -> I know this does not make sense

2nd method

      try {
          var files = (here the list of files should come. However i am failing to get those);
          var path="./"
          files.forEach(path => fs.existsSync(path) && fs.unlinkSync(path))
        } catch (err) {
          console.error("not exist")
        }

Any different approaches would be appreciated.

Update for the solution:

I have got the solution for my requirement, I just wanted my function to delete all the pdf files and function to be synchronous. However 99% of the solution given by the below author -> https://stackoverflow.com/a/66558251/11781464

fs.readdir is asynchronous and just needs to make it synchronous fs.readdirSync.

below is the updated code and all the credit should go to the author https://stackoverflow.com/a/66558251/11781464.

Updated code

        try {
          const path = './'
          // Read the directory given in `path`
          fs.readdirSync(path).forEach((file) => {
              // Check if the file is with a PDF extension, remove it
              if (file.split('.').pop().toLowerCase() === 'pdf') {
                console.log(`Deleting file: ${file}`);
                fs.unlinkSync(path + file)
              }
            });
          console.log("Deleted all the pdf files")
          return true;
        } catch (err) {
          console.error("Error in deleting files",err);
        }
RAJENDRA H
  • 83
  • 10
  • Do you want to delete all of the pdf's in the current working directory or only some of them? If only some, what is the criteria that determines which files to delete? – traktor Mar 10 '21 at 03:18
  • hi @traktor, I want to delete all the different pdf files in the same directory, I have updated the above question, thank you for looking into this. – RAJENDRA H Mar 10 '21 at 03:24

4 Answers4

1

You can read the directory using fs.readdir and then check for PDF files and delete them. Like this:

fs = require('fs');

try {
  path = './'
  // Read the directory given in `path`
  const files = fs.readdir(path, (err, files) => {
    if (err)
      throw err;

    files.forEach((file) => { 
      // Check if the file is with a PDF extension, remove it
      if (file.split('.').pop().toLowerCase() == 'pdf') {
        console.log(`Deleting file: ${file}`);
        fs.unlinkSync(path + file)
      }
    });
  });
} catch (err) {
  console.error(err);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Haseeb Jehanzeb
  • 319
  • 5
  • 9
0

Preliminary Reading


Example

"use strict";
const fs = require('fs');
const path = require('path');
const cwd = process.cwd();

fs.readdirSync( cwd, {withFileTypes: true})
.forEach( dirent => {
    if(dirent.isFile()) {
        const fileName = dirent.name;
        if( path.extname(fileName).toLowerCase() === ".pdf") {
            fs.unlinkSync( path.resolve( cwd, fileName));
        }
    }
});

Notes

  1. untested code
  2. If unlinkSync fails I would assume it returns -1 as per the unlink(2) man page linked in documentation. Personally I would test this using a filename that doesn't exist in cwd.
  3. I believe the {withFileTypes: true} option for readdirSync returns dirent objects with a mime-type value that would allow you to check for files of type application/pdf regardless of extension (not attempted in the example).

Update: path(resolve) adds the current working directory at the beginning of the returned path, when necessary, by default. path.resolve(fileName) will work equally as well as path.resolve(cwd, fileName) in the example.

traktor
  • 17,588
  • 4
  • 32
  • 53
0

It seems you know how to delete (unlink) the files - you are asking how to get the file paths?

Try using glob:

const pdfFiles = require("glob").globSync("*.pdf");
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
0

Hi here i am attaching tested code for delete all ( only ) .pdf files and not other extension files like .txt , .docs etc from directory.

Note : You can delete any files or directory only from server side.

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

fs.readdir('../path to directory', (err, files) => {
const pdfFiles = files.filter(el => path.extname(el) === '.pdf')
pdfFiles.forEach(file => {
    console.log("Removing File -> ",file);
    var filename = "../path to directory/"+file;
    fs.unlink(filename,function(err){
        if(err) return console.log(err);
        console.log('file deleted successfully');
   });  
  });
});

This will gives you a following result in console log.

Removing File -> note.pdf
Removing File -> note2.pdf
file deleted successfully
file deleted successfully

Please feel free to comment any query if have..