Node file system fs.exist strikethrough
Answer a question
This backend code retrieves an image file from the uploads/users folder. Visual Studio Code marks fs.exists with strikethrough, what does it means? It's deprecated? How can i replace this? Thanks in advance.
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'});
}
});
}
Answers
Yes, fs.exists
is deprecated, one reason is that
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 is pretty clear about this and recommended alternatives (fs.stat
and fs.access
)
The real problem in your code is the race condition you could encounter in your callback if for example that file gets deleted meanwhile. A safest way would be:
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...
}
}
})
Other common system errors are here.
更多推荐
所有评论(0)