Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
How to return promise from fs.unlink

I want to delete a file and wait for the deletion to succeed before moving forward. I have used unlink function inside a promise to get the result, but when unlink done successfully then I am getting the result from the promise if there is any kink of error while deleting the file the promise does not return any error.

Service:

public removeUserImage(
   user: User,
): Promise<NodeJS.ErrnoException | boolean> {
   const pathToRemoveImage = 'src/public/uploads'+ '/' + user.image_url;

   return new Promise((resolve, reject) => {
       unlink(pathToRemoveImage, (error) => {
          if (error) reject(error);
          resolve(true);
       });
    });
 }

Controller:

const isFileRemoved = await this._userService.removeUserImage(user);

//This block not excuting
if (!isFileRemoved) {
    throw new InternalServerErrorException(
        'Error occurred while trying to remove file.',
    );
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your promise rejects if there's an error. When using await, you need to wrap the code in try..catch in order to handle any failures

try {
  await this._userService.removeUserImage(user);
} catch (err) {
  console.error(err);
  throw new InternalServerErrorException(
    'Error occurred while trying to remove file.'
  );
}

FYI, you can (and should) use the Promises API versions of the fs functions

import { unlink } from "node:fs/promises";

public removeUserImage({ image_url }: User): Promise<void> {
  const pathToRemoveImage = `src/public/uploads/${image_url}`;

  return unlink(pathToRemoveImage);
}

If you wanted your method to always resolve with a Boolean, you'd want something like

return unlink(pathToRemoveImage)
  .then(() => true) // resolve with "true" for success
  .catch((err) => {
    console.error("removeUserImage", image_url, err);
    return false; // resolve with "false" for failure
  });
about 4 years ago · Juan Pablo Isaza Relatório

0

The error will always go to catch block,

try {
  await this._userService.removeUserImage(user);
} catch (err) {
  console.error(err);
  throw new InternalServerErrorException(
    'Error occurred while trying to remove file.'
  );
}

Suggestion: You don't need to convert unlink(callback) to promise fs has promise function also, check this

const fs = require('fs');
const fsPromises = fs.promises;

public removeUserImage(
   user: User,
): Promise<void> {
   const pathToRemoveImage = 'src/public/uploads'+ '/' + user.image_url;
   return fsPromises.unlink(pathToRemoveImage);
 }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda