仅在图像已经存在时如何删除

时间:2019-01-21 15:57:31

标签: javascript node.js express ejs

我正在开发Node.js + Express.js Web应用程序。

我创建了一个用户个人资料页面,允许用户输入个人信息和照片。

我想确保如果用户上传新照片,则应该删除旧图像。

现在,如果用户是第一次上传照片,则覆盖旧照片但我的代码可以正常工作,然后崩溃并显示500错误页面。

我该如何解决?

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

我在终端日志中得到了

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

根据请求添加! deleteFile方法的代码

const fs = require('fs');

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

exports.deleteFile = deleteFile;

2 个答案:

答案 0 :(得分:0)

此函数会引发错误吗?

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

}

答案 1 :(得分:0)

请对您的代码进行以下更改,它会为您工作正常。

新代码如下:

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