File deletion with Fs not working

Asked

Viewed 149 times

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 answers

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 => {})

  • 2

    I think it is worth mentioning in the answer that the version that uses the promises is not exported directly by require('fs'), but yes require('fs').promises, and later versions of Node.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.