Node module restarting on multiple requests

0

I'm developing a personal project to do performance testing on a list of sites and for this I'm using the lighthouse modules and chrome-launcher. In my application is being read a list of sites (url) and the requisitions are made to the lighthouse where the data is returned. The problem in question is that this module after being called it restarts out of nowhere and it keeps running 2x or more at the same time. I'm using promises to make these interactions. I used different methods to make the requisition. First I tried to use the Q giving a resolve when the lighthouse response returned. I also tried to use the promise and inside it a for and I am currently using the promise with a recursive function and in the 3 cases the same problem happened

Followthesourceinquestion:

constfs=require('fs');constrequest=require('request');constcheerio=require('cheerio');constlighthouse=require('lighthouse');constchromeLauncher=require('chrome-launcher');constQ=require('q');require('q-foreach')(Q);module.exports.refreshData=function(application,req,res){console.log('\n\n\ncaiunomodulo\n\n\n');//Listadesitesfs.readFile('./clientes.json',function(err,data){if(err)throwerr;if(typeofdata=='object'&&data.length>0){json=JSON.parse(data);}else{json=[];}apiCall(json);});functionapiCall(response){varjson=[];vari=0;constopts={chromeFlags:['--headless','--disable-gpu']};fs.writeFile("./result.json", '', function(err){
            if(err) {
                console.log(err);
                return;
            }
        });        

        console.log('\n\nN° de clientes do Magazord: ${response.length}\n\n');

        auditClient = new Promise((resolve, reject) => {
            auditClient = audit(0);

            function audit(indexOfExec){
                let element = response[indexOfExec];
                let cliente = element['Cliente'];
                let url = element['Site URL'];
                let resultClients = [];

                chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => {
                    opts.port = chrome.port;
                    console.log('${indexOfExec + 1} - Verificando o cliente ${cliente}');

                    lighthouse(url, opts, null).then(results => {
                        chrome.kill().then(function(){
                            resultClients.push({
                                clienteNome: cliente,
                                clienteUrl: url,
                                favicon: url + 'image/favicon.png',
                                logo: url + 'image/logo.png',
                                performance: ((results.lhr.categories.performance.score) * 100).toFixed(0),
                                pwa: ((results.lhr.categories.pwa.score) * 100).toFixed(0),
                                accessibility: ((results.lhr.categories.accessibility.score) * 100).toFixed(0),
                                bestPractices: ((results.lhr.categories['best-practices'].score) * 100).toFixed(0),
                                seo: ((results.lhr.categories.seo.score) * 100).toFixed(0),
                                errosConsole: {
                                    'quantidade': results.lhr.audits['errors-in-console'].rawValue,
                                    'detalhes':  results.lhr.audits['errors-in-console'].details
                                },
                                requisicoes: results.lhr.audits['network-requests'].rawValue,
                                otimizacaoImagens: ((results.lhr.audits['uses-optimized-images'].score) * 100).toFixed(0),
                                tempoCarregamento: (results.lhr.audits.metrics.details.items[0].firstContentfulPaint).toFixed(2).slice(0, 3),
                                speedIndex: (results.lhr.audits['speed-index'].rawValue).toFixed(2).slice(0, 3),
                                dataAtualizacao: getDateTime()
                            });

                            fs.writeFile('./audit-clients/${slug(cliente)}.json', JSON.stringify(results.lhr), {flag: 'w+'}, function(err){
                                if(err){
                                    return console.log('Erro ao tentar gravar os dados do audit do cliente ${cliente} ' + err);
                                }
                            })

                            fs.readFile('./result.json', {flag: 'rs+'}, function (err, data) {
                                if(err) {
                                    return console.log('Erro ao tentar recuperar os resultados do result.json ' + err);
                                }

                                if(typeof data == 'object' && data.length > 0){
                                    json = JSON.parse(data);
                                } else {
                                    json = [];
                                }

                                json.push(resultClients)

                                fs.writeFile("./result.json", JSON.stringify(json), {flag: 'w+'}, function(err){
                                    if(err){
                                        return console.log('Erro ao tentar salvar os resultados no result.json ' + err);
                                    }
                                });
                            });

                            console.log('Finished - ${cliente}\n');

                            if(indexOfExec < response.length -1){
                                audit(indexOfExec + 1)
                            }else{
                                console.log('Informações atualizadas com sucesso!');
                                resolve(resultClients);
                            }
                        })
                    })
                });
            }
        });
    }


    function renderView(data){
        res.end(JSON.stringify(data));
    }
}

The project I put in the github for easy visualization

    
asked by anonymous 23.08.2018 / 22:38

0 answers