简体   繁体   中英

How to delete image only if it already exists

I'm working on a Node.js + Express.js web application.

I have created a user profile page that allows a User to input personal information and a photo.

I want to make sure that if a user uploads a new photo then the old image should be deleted.

Now my code works fine when it comes to overwriting an old photo BUT if a user is uploading a photo for the first time then it crashes with 500 error page.

How can I fix this ?

exports.postEditCustomerProfile = (request, response, next) => {
    const firstName = request.body.firstName;
    const lastName = request.body.lastName;
    const phone = request.body.phone;
    const address = request.body.address;
    const image = request.file;
    const UserId = request.user._id;

    const errors = validationResult(request);
    if (!errors.isEmpty()) {
        return response.status(422).render('site/edit_customer', {
            pageTitle: 'Edit Customer',
            path: '/edit_customer',
            user: {
                email: request.user.email,
                firstName: firstName,
                lastName: lastName,
                phone: phone,
                address: address,
            },
            errorMessage: errors.array()[0].msg,
            validationErrors: errors.array()
        });
    }

    User.findOne(UserId)
        .then(user => {
            user.firstName = firstName ? firstName : user.firstName;
            user.lastName = lastName ? lastName : user.lastName;
            user.phone = phone ? phone : user.phone;
            user.address = address ? address : user.address;
            if (image) {

                //This line of code should delete the old photo before uploading the new photo.
                fileHelper.deleteFile(user.photoUrl);

                user.photoUrl = image.path;
            }
            return user.save();
        })
        .then(result => {
            console.log('Updated Customer Profile Info');
            response.redirect('/edit-customer');
        })
        .catch(err => {
            const error = new Error(err);
            error.httpStatusCode = 500;
            return next(error);
        });
};

I get this in the terminal log

Error: ENOENT: no such file or directory, unlink ''

Added per request! The code for deleteFile method

const fs = require('fs');

const deleteFile = (filePath) => {
    fs.unlink(filePath, (err) => {
        if (err) {
            throw (err);
        }
    })
}

exports.deleteFile = deleteFile;

Would this answer the problem, as the function throws an error?

try {
  fileHelper.deleteFile(user.photoUrl);
}
catch(err) {

}

Please do the below change to your code and it will work fine for you.

New Code will look like:

if (user.photoUrl) {
            //This line of code should delete the old photo before uploading the new photo.
            fileHelper.deleteFile(user.photoUrl);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM