Read txt file and do javascript validations

2

I have a txt file that contains more than a thousand lines, each line has a number that needs to be validated by a javascript script that I have ready.

I would like some script in php or javascript even read the file in txt, take line by line and validate with the other validation script that I have, and when validated, if the line fails in validation, excluded or at least marked with some special character, but I'd rather be removed anyway.

Note: I have Linux servers that would handle processing if the solution requires a lot of the machine.

Simple verification that would be used:

var numero = "55555555555"; // Aqui no caso seria puxado o arquivo em txt
if(numero.match(/55555555555/))
{ document.write("OK"); } else{
document.write("Nao Passou");}

Is there any way to do this?

    
asked by anonymous 27.10.2017 / 23:32

2 answers

3

As I said, with JavaScript running in the browser it will not be possible - simply because JavaScript does not have access to the files. You have commented that they are simple validations, it will be more feasible to implement them in PHP and execute everything with this language.

To open and read the contents of a file, you can use the file :

<?php

$file = file("arquivo.txt");

if ($file !== false)
{
    foreach($file as $index => $line)
    {
        // Validação da linha...
    }
}

Based on your comments, the validation quoted would be if the line value matches the /55555555555/ , set by a regular expression. Considering that when the contents of the line do not match this pattern the line should be deleted, one can do:

<?php

$file = file("arquivo.txt");

if ($file !== false)
{
    foreach($file as $index => $line)
    {
        if (!preg_match("/55555555555/", trim($line), $matches))
        {
            unset($file[$index]);
        }
    }
}

Thus, the array $file , after finishing the loop repeat, will have only the values that have passed the validation. To re-write the file, simply use the file_put_contents function in conjunction with the < a href="http://php.net/manual/en_US/function.implode.php"> implode :

file_put_contents("arquivo.txt", implode("", $file));

Documentation

28.10.2017 / 00:29
0

Using JavaScript with Ajax

The script below will go through line by line of the file .txt , excluding the lines that do not have the desired string and updating the file in real time:

Filefiltrar.php:

<?php$conteudo=$_GET['cont'];$arquivo=$_GET['arquivo'];if(isset($conteudo)&&isset($arquivo)){$fp=fopen($arquivo,"r");
    $texto = fread($fp,filesize($arquivo));
    fclose($fp);

    $fp = fopen($arquivo,"w");
    $nconteudo = str_replace($conteudo, '', $texto);
    $nconteudo = str_replace(str_replace("\n", '', $conteudo), '', $nconteudo);
    fwrite($fp,rtrim($nconteudo));
    fclose($fp);
}else{
?>
<html>
<head></head>
<body>
<input type="button" value="Iniciar" id="inicio" />
<br /><br />
<div id="processamento">
</div>

<script>

verificar = "55555555555"; // o que quer verificar. Será excluída a linha que não conter isso
meu_arquivo = "arquivo.txt"; // nome do arquivo de origem
tempo_linha = 1; // intervalo de processamento de cada linha, em segundos

var arq = new XMLHttpRequest();
conteudo_idx = 0;
contador = 1;
div_processa = document.getElementById("processamento"); // div com resultados
function lerTexto(arquivo){
    arq.open("GET", arquivo, false);
    arq.onreadystatechange = function(){
        if(arq.readyState == 4){
            conteudo = arq.responseText.split("\n");
            div_processa.innerHTML = "Processando "+conteudo.length+" linhas:<br />";
            processa();
        }
    }
    arq.send(null);
}

function processa(){
    if(conteudo_idx < conteudo.length){
        if(conteudo[conteudo_idx].match(verificar)){
            div_processa.innerHTML = div_processa.innerHTML+"&bull; Linha "+contador+": Passou!<br />";
            setTimeout("processa()",tempo_linha*1000);
        }else{
            div_processa.innerHTML = div_processa.innerHTML+"&bull; Linha "+contador+": Não passou!<br />";
            arq.open("GET", "filtrar.php?cont="+encodeURIComponent(conteudo[conteudo_idx]+'\n')+"&arquivo="+meu_arquivo, false);
            arq.onreadystatechange = function(){
                if(arq.readyState == 4){
                    setTimeout("processa()",tempo_linha*1000);
                }
            }
            arq.send(null);
        }
        conteudo_idx++;
        window.scrollTo(0,document.body.scrollHeight);
    }else{
        div_processa.innerHTML = '<strong>Processo finalizado!</strong><br />'
        +'<strong style="color: green;">Arquivo <a href="'+meu_arquivo+'" target="_blank">'+meu_arquivo+'</a> gravado!</strong><br />'
        +div_processa.innerHTML;
        scroll(0,0);
    }
    contador++;
}

document.getElementById("inicio").addEventListener('click', function(){
    lerTexto(meu_arquivo+"?"+Math.random());
    this.outerHTML = '';
});

</script>

</body>
</html>
<?php
}
?>
  

Necessary that the files be in the same directory and that the same one has authorization for reading and writing.

    
28.10.2017 / 15:45