2
I have a if
to delete a file, however it is not being deleted and is not throwing errors.
Does anyone have any idea?
if (results[0].photo != `arquivos/imgpadrao.jpg`) {
fs.unlink(`./public/${results[0].photo}`);
}
2
I have a if
to delete a file, however it is not being deleted and is not throwing errors.
Does anyone have any idea?
if (results[0].photo != `arquivos/imgpadrao.jpg`) {
fs.unlink(`./public/${results[0].photo}`);
}
3
You are using an asynchronous method (fs.unlink
), waiting for a callback for when it is solved. Thus, you should use a function of callback to see if there were any mistakes:
if (results[0].photo !== `arquivos/imgpadrao.jpg`) {
fs.unlink(`./public/${results[0].photo}`, (err) => {
if (err) {
console.log('Houve algum erro!', err);
} else {
console.log('Tudo certo! Arquivo removido.');
}
});
}
You can also use the synchronous version of this method, fs.unlinkSync
, performing the error procedure with a try
/catch
:
if (results[0].photo !== `arquivos/imgpadrao.jpg`) {
try {
fs.unlinkSync(`./public/${results[0].photo}`);
console.log('Tudo certo!');
} catch (err) {
console.log('Houve algum erro!', err);
}
}
2
Use the unlinkSync
to exclude:
fs.unlinkSync(`./public/${results[0].photo}`);
Or use the Promise
fs.unlink(`./public/${results[0].photo}`).then(res => {}).catch(err => {})
Browser other questions tagged javascript node.js fs
You are not signed in. Login or sign up in order to post.
I think it is worth mentioning in the answer that the version that uses the promises is not exported directly by
require('fs')
, but yesrequire('fs').promises
, and later versions of Node.– Luiz Felipe