Is it possible to read a. txt file in Javascript?

Asked

Viewed 8,130 times

2

If possible, how would I do that? I have a file called version., and I need Javascript to read it and show its content on the screen. Does anyone have any idea how they would do that? PS: Please would like a code without using functions json.

  • related https://answall.com/questions/221254/setar-um-arquivo-de-texto-no-servidor-a-ser-lido-sempre-que-executar-o-html-co/221264#221264

  • Where is your file? On the server or client?

  • 1

    on my localhost, I need to test with it first here, then move to the server..

  • localhost tb is server... or not? :)

  • I’m racking my brain with this, I don’t get along with Web >-<, sorry

  • @Alis We’re here to learn and help each other. No need to apologize =]

  • um.. Thank you really

Show 2 more comments

2 answers

5

I believe with a simple XMLHttpRequest this is possible. Remember that server requests are asynchronous, so they are not executed in the order you read the code. That’s why we always provide callbacks for them, which is the code we want you to execute when this request comes back from the server.

//esta variável é um array de arrays. Cada posição do array
// é um array de duas posições. a primeira é uma URL, e a segunda um callback
var urls = [
  ['https://jsonplaceholder.typicode.com/posts/1', mostrarNaTela],
  ['https://jsonplaceholder.typicode.com/posts/2', logarNoConsole],
  ['https://jsonplaceholder.typicode.com/posts/3', escreverNaTela]
]

// #### estes são os callbacks. Eles também podem ser funções anônimas, mas para evitar o callback hell, prefiro assim
function mostrarNaTela(conteudo){ alert(conteudo); }
function logarNoConsole(conteudo) { console.log(conteudo); }
function escreverNaTela(conteudo) { document.write(conteudo); }
// #### fim dos callbacks

// esta função destrincha o array na posição pedida, pegando o callback e a url
function fazerRequest(url){
// variável dados é um array de duas posições
  var dados = urls[url];
  //uri é a url aonde farei a requisição
  var uri = dados[0];
  //callback é a função que será executada na volta da requisição
  var callback = dados[1];
  lerArquivo(uri, callback);
}

function lerArquivo(nome, callback)
{
    var req = new XMLHttpRequest();
    req.open("GET", nome, false);
    req.onreadystatechange = function ()
    {
        if(req.readyState === 4)
        {
            //verifica se a requisição foi bem sucedida
            if(req.status === 200 || req.status == 0)
            {
                callback(req.responseText);
            }
        }
    }
    req.send(null);
}
<button id="acao1" onclick="fazerRequest(0)">Mostrar na tela</button>
<button id="acao2" onclick="fazerRequest(1)">Mostrar no console</button>
<button id="acao3" onclick="fazerRequest(2)">Mostrar no HTML</button>

  • but where do I enter with the name of my file?.... sorry I don’t understand much about AJAX

  • Only replace on the invocation of lerArquivo. Remember that if the request is cross-domain, this must be enabled, otherwise it will give error

  • Already predicting the next question, it would be nice to pass a callback to this function.

  • @bfavaretto will edit with some callbacks :)

  • I would recommend an example with fetch because it is more succinct, use Promise and already returns an object (in case it is a json)

  • @Lauromoraes I’m not so familiar with Promises to the point of writing them as an answer :( so I opted for even common callbacks

  • What you’re talking about, I’m very nuub people in this area, I know you’re trying to help me and I really appreciate it but I don’t understand anything... sorry

  • @Alis Esse callback that Artur included in the answer you will need, go for me. You will only have access to the contents of the file from within this callback function.

  • @bfavaretto , What would be a callback Hell?

  • 1

    @Alis a callback Hell, or callback hell, is when you fall into an indistinguishable tangle of nested functions, take a look here: https://answall.com/questions/188656/o-que-%C3%A9-o-inferno-dos-callbacks

  • @bfavaretto, thank you very much. I managed to modify the code in some way to stay the way I need. I really appreciate your willingness and your kindness in helping. Thank you !!

Show 6 more comments

1

Although XMLHttpRequest be supported by the widest range of browsers I would recommend using the API Fetch she works on XMLHttpRequest and is more recent abstracting in much the heavy work.

Like this API uses Promise makes it easier to handle errors and exceptions.

A basic example:

var request = function(url) {

    fetch(url, {
        cache: 'reload' // definir o tipo de cache
    }).then(function(response) {
        if ( response.ok ) {
            // texto simples
            return response.text();
            // para transformar o `json` que é `string` para um `object`
            // javascript use `response.json()` que o próximo `then` retornará um `object`
        }
        // em caso de resposta "opaca" ou outros erros
        throw new Error('Fetch error, status code: ' + response.status);
    }).then(function(text) {
        // buscar elemento (div)
        var el = document.getElementById('container');
        // adicionar resultado (objeto para string)
        el.innerHTML = el.innerHTML += '<br>' + text;
    }).catch(function(error) {
        // caso haja um erro... tratar aqui
    });

};
<button type="button" onclick="request('https://jsonplaceholder.typicode.com/posts/1');">adicionar ao elemento (div)</button>


<div id="container">Resultado:</div>

The current support of API Fetch: (source: caniuse with.)

inserir a descrição da imagem aqui

Browser other questions tagged

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