Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda