I have a script which is supposed to delete the files which have a file type of PDF in a specific path upon a button being pressed, this is my code.
<a class="btn btn-primary" href="{{ pdflocation }}" id='downloadbutton' role="button">đDownload</a>
<script>
function deletepdf() {
try {
const path = 'C:/Users/Arshia's PC/PycharmProjects/Flask/static/'
// 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);
}
}
document.getElementById('downloadbutton').onclick = deletepdf()
</script>
This is my JavaScript script but it doesn't seem to work at all when I click the button which has the ID 'downloadbutton', I'm using Flask and I also tried this alternative
os.remove(f"C:/Users/Arshia's PC/PycharmProjects/Flask/static/" + pdfname)
and this works but the only problem is that this deletes the file I need before it is uploaded to the static folder so it cannot be uploaded in time, so the only logical solution is to delete the file when the button is pressed as that is also when it is being uploaded. I'm not sure what's wrong with my JavaScript code and was wondering what I should do to fix it, I thought it might be the path but I tried many different path's and it still didn't work so I'm a bit confused. I got the script from another Stack Overflow post and since I'm using Flask the console logs are useless so that may be what is causing the issue but I'm not entirely sure.