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?
Advertisement
Answer
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 ); }); });