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

303
Vistas
Creating a ZIP file in JS
async acquistoMultiplo(decoded, datiAcquisto){

    const utente = await Database.utente.findOne({where: { id_utente: decoded.id_utente }});
    if( ! utente) return [404, 'ERRORE: utente [' + decoded.id_utente + '] non trovato'];
    
    if(utente.credito<datiAcquisto.length) return [401, 'ERRORE: credito residuo insufficiente'];

    const zip = new JSZip();
    
    for(let i = 0; i < datiAcquisto.length; i++){
      let prodotto = await Database.prodotto.findOne({where: { id_prodotto: datiAcquisto[i].id_prodotto, disponibile: true}});
      if(! prodotto) return [404, 'ERRORE: prodotto [' + datiAcquisto[i].id_prodotto + '] non trovato o momentaneamente non disponibile!'];

      const fileFS = fs.readFileSync(prodotto.link);
      zip.file(prodotto.link, fileFS);
    }
      
    const dataAcquisto = getDataCorrente();

    for(let i = 0; i < datiAcquisto.length; i++){

      const acquistoPresente = await Database.acquisto.findOne({where: {utente: utente.id_utente, prodotto: datiAcquisto[i].id_prodotto}});
      if( ! acquistoPresente)  {
        const acquistoSalvato = await Database.acquisto.create({ utente: utente.id_utente, prodotto: datiAcquisto[i].id_prodotto, data_acquisto: dataAcquisto, originale: true});
        if( ! acquistoSalvato) return [500, 'ERRORE SERVER: impossibile salvare l\'acquisto'];
      } else {
        const acquistoSalvato = await Database.acquisto.create({ utente: utente.id_utente, prodotto: datiAcquisto[i].id_prodotto, data_acquisto: dataAcquisto, originale: false});
        if( ! acquistoSalvato) return [500, 'ERRORE SERVER: impossibile salvare l\'acquisto'];
      }
    }

    // aggiorna credito residuo dell'utente
    const creditoResiduo = utente.credito-datiAcquisto.length;
    const creditoAggiornato = await Database.utente.update({ credito: creditoResiduo }, {
        where: {
          id_utente: utente.id_utente
        }
      });
    if( ! creditoAggiornato) return [500, 'ERRORE SERVER: impossibile aggiornare il credito residuo'];
    
    zip.generateNodeStream({type:'nodebuffer',streamFiles:true})
       .pipe(fs.createWriteStream('./files/out.zip'))
       .on('finish', function(){
            console.log('file zip creato');
    });


    zip
      .generateInternalStream({type:"uint8array"})
      .accumulate(function updateCallback(metadata) {
          // metadata contains for example currentFile and percent, see the generateInternalStream doc.
      }).then(function (data) {
          // data contains here the complete zip file as a uint8array (the type asked in generateInternalStream)
          fs.createWriteStream('./files/out.zip');
      });



    return ['./files/out.zip'];
  }

This is my file. I am not able to let the program wait to finish the creation of the zip file before to execute the return function. What I am doing wrong? I know that this i an async function that create the zip file. What can I do? I need help to fix this problem. I dont know what i need to write more

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you will need to use a promise and await the the process of zip file creation before returning:

//...

await (() =>
  new Promise((resolve, reject) => {
    zip
      .generateNodeStream({ type: "nodebuffer", streamFiles: true })
      .pipe(fs.createWriteStream("./files/out.zip"))
      .on("finish", function () {
        console.log("file zip creato");

        resolve();
      });
  }))();
  
return ['./files/out.zip'];

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