节点文件系统 fs.exist 删除线

Node file system fs.exist strikethrough

此后端代码从 uploads/users 文件夹中检索图像文件。 Visual Studio 带删除线的代码标记 fs.exists 是什么意思?它被弃用了吗?我该如何替换它?提前致谢。

getImageFile: (req, res) => {
        let file = req.params.image;
        let pathFile = './uploads/users/' + file;
    
        fs.exists(pathFile, (exists) => {
            if(exists){
                return res.sendFile(path.resolve(pathFile));
            } else {
                return res.status(200).send({message: 'No existe la imagen'});
            }
        });
    }

可能是因为 fs.exists is deprecated 你不应该在新代码中使用它。

是的,fs.exists 已弃用,原因之一是

The parameters for this callback are not consistent with other Node.js callbacks. Normally, the first parameter to a Node.js callback is an err parameter, optionally followed by other parameters. The fs.exists() callback has only one boolean parameter.

Documentation 对此和推荐的替代方案非常清楚(fs.statfs.access

您代码中的真正问题是您可能会在回调中遇到竞争条件,例如,如果该文件同时被删除。最安全的方法是:

res.sendFile(path.resolve(pathFile), function (err) {
    if (err) {
        if (err.code === 'ENOENT') {
            return res.status(200).send({message: 'No existe la imagen'});
        }
        else {
            // handle other errors...
        }
    }
})

其他常见的系统错误是 here