Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete local file with fs.unlink?

CODE:

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');                                
        }
});

ERROR MESSAGE IN CONSOLE/TERMINAL:

failed to delete local image:Error: ENOENT: no such file or directory, unlink '/public/images/uploads/ed6d810405e42d0dfd03d7668e356db3'

SITUATION

I must have specified the wrong path. I don't understand why it would be wrong, the "public" folder is at the same level as the "app.js" file. The "upload.js" is in a folder called "routes" which is at the same level as "app.js".

And I have specified a route "/public" to my public folder in my app.js:

//Static Folder
app.use("/public",express.static(path.join(__dirname, "/public")));

QUESTION:

What have I done wrong ?

like image 960
Coder1000 Avatar asked Dec 31 '16 20:12

Coder1000


People also ask

How can you remove a file using node's fs module?

js fs-extra remove() Function. the remove() function deletes the given file or directory. All the files inside a directory are deleted.

What is the use of fs unlink () method?

The fs. unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs. rmdir() to remove a directory.

Which method of fs module is used to delete a file?

To delete a file with the File System module, use the fs.unlink() method.


2 Answers

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');                                
        }
});
like image 133
mitch Avatar answered Oct 04 '22 11:10

mitch


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.

like image 42
William Hou Avatar answered Oct 04 '22 13:10

William Hou