How to delete local file with fs.unlink?
I bet you want to delete file inside project directory. Try with this (dot before "/"):
fs.unlink("./public/images/uploads/"+req.file.filename, (err) => {
if (err) {
console.log("failed to delete local image:"+err);
} else {
console.log('successfully deleted local image');
}
});
You missed a part of the path. What you're showing is not enough, but it can be fixed in the following way:
For example, the path I got of a file is the following:
'C:\001-Training\MEANCourse\http:\localhost:3000\images\1-1571080310351.jpeg'
But actually the path is
'C:\001-Training\MEANCourse\http:\localhost:3000\backend\images\1-1571080310351.jpeg'
Here, the "MEANCourse" is my project name, and "backend" is the top-level folder name as "src", but when the path was produced automatically, the top-level folder was ignored.
So I added "backend" to the path, and it started to work.
You have to find out what part is missing in your case.
You do not need to use c:\
for you may not be in the windows environment. Also, you may be finally executing this in cloud etc. Instead, use a relative directory by using __dirname
. Like, if using backtick, do ${__dirname}
then add the rest of the directory, relative to the javascript file your code is in.