1

I want to delete a file named myfile with any extension.

const fs = require('fs')
const ext = '' ; //this extension may be anything
const path = './myfile.'+ext ;

fs.unlink(path, (err) => {
    if (err) {
        console.error(err)
        return
    }
    //file removed
})

The error I get:

no such file or directory named myfile

But there is a file named myfile.jpg which I want to delete. Let's pretend that we don't know the extension. How can I delete it?

6
  • Does this answer your question? How do I get a list of files with specific file extension using node.js? Commented Dec 29, 2020 at 3:44
  • Added a link that shows how to find all files and then match extension. unlink needs to be given a specific path so you first have to find all the files to remove beforehand. Commented Dec 29, 2020 at 3:44
  • There is no magic function. You have to write your own algorithm. Get a list of all files in the directory. For each file name in the array find all that match the name you want (you can easily do this with filter: array.filter(x=>x.match(/^myfile.*/)) or if you are not familiar with regexp array.filter(x=>x.substr(0,7) === 'myfile.')). Then for each filename found delete it Commented Dec 29, 2020 at 3:45
  • @slebetman thank you ,but will this method take a lot of time if we have thousands of files, because it have to fetch them all . Commented Dec 29, 2020 at 4:08
  • Any method, even one that seem magical by allowing you to specify a pattern for the filename, will have to traverse the disk to find the files. That is just how hard disks and filesystems work (there are indexing systems in various OSes that can speed up searching the entire disk but usually searching a single folder is faster to old way - also, you can't trust everyone enabling the indexing system except for Spotlight on Mac OS where most people don't know how to turn it off) Commented Dec 29, 2020 at 9:32

1 Answer 1

3

unlink doesn't support regex to delete file. You will probably need to loop through the the folder and find the filename start with 'myfile' and delete it accordingly.

const fs = require('fs');
const director = 'path/to/directory/'

fs.readdir(directory, (err, files) => {
    files.forEach(file => {
        if(file.split('.')[0] == 'myfile') fs.unlink( directory + file );       
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

So the idea of this method is to fetch the directory to find any file with that name.. This will also work if we have multiple files with the same name and different ext, thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.