Program does not return to the loop after executing function

Asked

Viewed 42 times

1

I have a robot that accesses an online system and downloads the files. It works with a delay between one download and another, but is taking time.

On this system, I can only close the open tab after the downloaded file.

For this I am doing the check if in 25 seconds (this time will be changed) the file of certain drive is downloaded, else it changes the drive to download a new file.

const puppeteer = require('puppeteer');
const fsReadDirRecGen = require('fs-readdir-rec-gen');
const fs = require('fs');
const path = require('path');
const { resolve } = require('path');
const { rejects } = require('assert');
const savedFolder = '/pasta_para_salvar_arquivos/'; 
const downloadFolder = '/pasta_downloads_win/'; 
const dirChrome = '/pasta_chrome_instalado/'; 
const prefix = "PrefixoArquivo";


var unidades = ['AAA', 'BBB', 'CCC', ...]; //array de unidades
var n = 0;

(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        executablePath: dirChrome,
        args: ['--start-maximized']
    })


    //ABERTURA DA PÁGINA
    const page = await browser.newPage();
    await page.setViewport({ width: 1366, height: 768 });
    await page.goto('https://sistema.com.br/'); //acessa o sistema
    .
    .
    .


    for (n = 0; n < unidades.length; n++) 
    {

        var unidadegen = unidades[n];

        
        await page.type('input[name="f2"]', unidadegen, { delay: 100 }); // AQUI SELECIONA A UNIDADE
        
        const pageTarget = page.target();
        const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
        const newPage = await newTarget.page(); // AQUI ABRE A NOVA ABA
        
        .
        .
        .
        
        await newPage.keyboard.press('Enter', { delay: 100 }); // AQUI É O SUBMIT DO FORMULÁRIO E O INÍCIO DO DOWNLOAD
        
        // await delay(60000); // Eu fazia um timeout de 1 minuto para fechar a aba, por isso criei a função abaixo

        await checkFile(fileVerify(prefix, unidadegen)); // CHAMA A FUNÇÃO PARA CHECAR O ARQUIVO

        
        await newPage.close(); //AQUI DEVERIA FECHAR A ABA ABERTA PARA VOLTAR O LOOP COM UMA NOVA UNIDADE
      
        
    } 
    await browser.close();  //fecha o navegador...
})();


function delay(time) {
    return new Promise(function (resolve) {
        setTimeout(resolve, time)
    });
}


// FUNÇÃO ASINCRONA E RECURSIVA QUE DURANTE 25 TENTATIVAS (DE 1 SEGUNDO CADA) 
// FICARIA VERIFICANDO SE O ARQUIVO FOI BAIXADO.


const checkFile = async(fileExists, attemps = 1) => {    
    return new Promise(async (resolve, rejects) => {        
        if(!fileExists && attemps <= 25){
            
            await delay(1000);                              
            return await checkFile(fileVerify(prefix, unidadeArquivo), ++attemps);            
        }
                   
        resolve('OK');
        
    })
}

// FUNÇÃO SINCRONA PARA VERIFICAR SE O ARQUIVO FOI BAIXADO, QUANDO O ARQUIVO FOI BAIXADO RETORNA TRUE

function fileVerify(prefix, unidadeArquivo) {    
    var temArquivo = false;    
    fs.readdirSync(downloadFolder).forEach(file => {
        if (file.startsWith(prefix) && file.endsWith(".sswweb")) {
            var arquivoBaixado = downloadFolder + "/" + path.basename(file); //arquivo q foi baixado agora pouco
            temArquivo = true;
            var arquivoAlterado = savedFolder  + unidadeArquivo + ".csv";
            fs.renameSync(arquivoBaixado, arquivoAlterado); 
                                
        }        
    });
    
    if(temArquivo){
        return true;
    }
    else{
        return false;
    }
}

I deleted some irrelevant lines from the code.

When I put a console.log in function checkFile, it is working to check the file during the 25 sec, and when it is found the file in the download folder the result is true, and the count ends.

My problem is that the execution is stopped after the process, I need to somehow return to the main process, which would close the tab of the drive I just downloaded and continue the loop to the next unit. I think I’ve done something wrong with this Promise.

No answers

Browser other questions tagged

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