Module Node restarting on multiple requests

Asked

Viewed 41 times

0

I am developing a personal project to perform performance tests on a list of websites and for this I am using the Lighthouse modules and Chrome-Launcher. In my application is being read a list of sites (url) and requests are made to Lighthouse where the proper data is returned. The problem in question is that this module after being called it restarts out of nowhere and it runs 2x or more at the same time. I am using files to make these interactions. I used different methods to make the request. First I tried using Q giving a resolve when Lighthouse’s sponse 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

inserir a descrição da imagem aqui

Follow the source in question:

const fs = require('fs');
const request = require('request');
const cheerio = require('cheerio');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const Q = require('q');
require('q-foreach')(Q);

module.exports.refreshData = function(application, req, res){
    console.log('\n\n\n caiu no modulo\n\n\n');

    //Lista de sites    
    fs.readFile('./clientes.json', function (err, data) {

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

        apiCall(json); 
    });

    function apiCall(response){
        var json = [];
        var i = 0;      

        const opts = {
            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 on github for easy viewing

  • If I clone your repository and run it will work?

  • @Sorack will work yes

No answers

Browser other questions tagged

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