Read txt file and validate javascript

Asked

Viewed 1,761 times

1

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 to even read the file in txt, take it line by line and be validated with the other validation script I have, and when validating, if the line is failed in validation, that it be excluded or at least marked with some special character, but I prefer that it be removed even if.

Obs: I have Linux servers that could handle processing if the solution requires too much of the machine.

Simple check 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 that?

  • This Javascript will be running in the browser or on the Node?

  • In the browser ...

  • What kind of validation is that? You can put it together with the question?

  • They are simple validations, but several, but an example would look like this: <script> var numero = "555555555555555"; // Here in case the txt file would be pulled if(numero.match(/55555555555/)){ Document.write("OK"); } Else{ Document.write("Not Passed"); } </script>

  • Ask the question, please. If they are simple validations, I recommend you implement them in PHP and do everything for this language. Use JS only if implementing this validation in PHP is not feasible.

  • But there’s no way I can do it the way I explained it?

  • In PHP, yes. It’s very easy, but I need you to clarify in the question what kind of validations are these.

  • Could you give me an example of how to do this in PHP if I were only to use a simple check if some line in the txt file found a numerical sequence, example 5555555555555? Because the rest I could change everything to php, I would only need an example.

  • You want to create the new txt file on the machine or on the server?

  • What is more feasible, because the result of this would be only for me, I would not put for users to run via browser, only myself would run this.

Show 5 more comments

2 answers

2


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

To open and read the contents of a file, you can use the function 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 whether the line value matches the default /55555555555/, defined by a regular expression. Whereas when the line content does 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 you have finished the loop, you will only have the values that have passed the validation. To write again in the file, just use the function file_put_contents together with the implode:

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

Documentation

  • Exactly that, solved my problem. Thank you.

  • It is possible by Javascript via Ajax.

  • @DVD only if a server is server the file via HTTP, but still could not save the file again. To save, you’d have to have one script running on the server side for this too. More practical to do everything in PHP even.

0

Using Javascript with Ajax

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

inserir a descrição da imagem aqui

Filing cabinet filtrar.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
}
?>

It is necessary that the files are in the same directory and that the same has authorization for reading and writing.

  • As I said, a solution with quite unnecessary complexity, as it will need a web server serving the text file and will need a script PHP on the server to save the new data. It is valid to post the answer as a matter of curiosity, but in my view, it would be a terrible way to solve the problem. The only situation I see this being plausible is when the validation was already implemented in JS and had a complexity so great that it would make it impossible to implement in PHP - which is extremely rare to happen.

  • @Andersoncarloswoss Your answer does not require a server to run?

  • No, only PHP (interpreter) installed.

  • @Andersoncarloswoss Blz. I don’t consider "unnecessary good" the solution I have proposed is only a very different form from your.

Browser other questions tagged

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