Search code examples
node.jsexpresshandlebars.jsfs

Delete file inside of a folder with delete router - Node.Js


I'm working on a Node.Js application where the user is able to upload and delete files.

On my 'app.delete' router I'm trying to pass the ID and the default name of the file. The 'ID' argument it's used to delete the object from the database and the default name is used to delete the image from my uploads folder by the name with unlink method.

Here is my 'app.js':

app.delete('/api/delete_welcome_screen_image/:id/:imageName', (req, res) => {
    fileStream.unlink('./uploads/' + req.params.imageName, err => {
        console.log(err);
    })

    ScreenImage.deleteOne(req.params._id)
    .then((screenImage) => {
        res.status(200).send(screenImage);
    })
    .catch(err => res.status(500).send(err));
})

...my HBS file with my HTML and JavaScript codes:


{{#each images}}
   <tr>
      <td>{{this.company}}</td>
      <td>{{this.date}}</td>
      <td>{{this.activated}}</td>
      <td>{{this.wsType}}</td>
      <td>
        <a href="/edit_welcome_screen_image/{{this.id}}" class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
        <a class="deleteImage" title="Delete" data-toggle="tooltip" href="/api/delete_welcome_screen_image/{{this.id}}/{{this.imageName}}"><i class="material-icons">&#xE872;</i></a>
      </td>
   </tr>
{{/each}}

$('.deleteImage').click((e) => {
        e.preventDefault();

        let confirmation = confirm("Are you sure about this?");

        if (confirmation === true) {
            $.ajax({
                type:'DELETE',
                url: '/api/delete_welcome_screen_image/:id/:imageName',
                contentType: 'application/json',
                success: (data) => {
                    alert('Welcome Screen deleted successfully!');
                    window.location.href = "/welcome_screens_list"
                },
                error: () => {
                    alert('An issue has occurred!');
                }
            })
        }
    })

This is the error I'm receiving:


{ [Error: ENOENT: no such file or directory, unlink 'C:\Users\paulo\Documents\Workspaces\Visual Studio Code\WelcomeScreenCinq\uploads\:videoName']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'unlink',
  path:
   'C:\\Users\\paulo\\Documents\\Workspaces\\Visual Studio Code\\WelcomeScreenCinq\\uploads\\:videoName' }

Everything is deleted correctly of my database but the image itself is not deleted of my uploads folder.

What am I doing wrong?


Solution

  • The problem is in your AJAX request. The :variables inside of the express route URL are parameters for data. You are not actually passing any data, you are passing in useless parameters.

    So, your AJAX request should be something like

                const id = //GET ID WITH jQUERY
                const imageName = //GET NAME WITH JQUERY
                $.ajax({
                type:'DELETE',
                url: `/api/delete_welcome_screen_image/${id}/${imageName}`,
                contentType: 'application/json',
                success: (data) => {
                    alert('Welcome Screen deleted successfully!');
                    window.location.href = "/welcome_screens_list"
                },
                error: () => {
                    alert('An issue has occurred!');
                }
            })
    

    Just a tip, you do not need to hand that ScreenImage name into the route. The ID should be enough to identify the resources to delete, because you should be renaming the files when they get uploaded with a unique identifier or you are going to have issues when someone else uploads a file with that name.