Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.2K
Visualizações
Validate if a file exists with JavaScript

Good day. I need to know if the file that I indicate in the path that I save in the text variable "t" as the slide variable "s" exist, in order to be able to show them or not through the view. I need to do this with only java script and local files, no server side. If possible, I would be very grateful to receive your help.

My current code in JavaScript:

function loadFiles(num) {

    let s = 'assets/content/Compiladores/Slides/' + num + '.jpg';
    let t = 'assets/content/Compiladores/Texts/' + num + '.txt';
    
    document.slider.src = s;
    $("#description").load(t);
    $("#num").text(num);

}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are never going to be able to reliably determine if a resource exists before doing something with it.

Note that this holds true even on a program that runs directly on a user's machine or a server. I don't normally mention other people's answers in my own, but the one advocating that you do that check (which per the link is problematic even in the best of circumstances) but across a client-server gap is sheer folly. Think about all the things that can go wrong:

  1. The server could have moved the resource between the time you check and the time you set it.
  2. Another thread or even entire other program could have acquired a lock on the resource causing your request to either take a lot of extra time or fail outright.
  3. The user could be on a mobile connection and lost signal between the time of the check and the time of the resource request.
  4. If you're passing an authentication token the user's session could expire between the time of the check and the time of the actual request.
  5. The server could crash between the first request and the second.
  6. The second request could be load-balanced to a different server than the first request.
  7. The entire network for a major service could go down between the requests. Yes, really.

And so on.

Not to mention that for the happy path it involves a completely unnecessary extra round trip to the server before you start showing them the thing you wanted to show them in the first place!

The correct way to do this is to attempt to load the resource and then just handle the error if it fails:

function loadFiles(num) {

    let s = 'assets/content/Compiladores/Slides/' + num + '.jpg';
    let t = 'assets/content/Compiladores/Texts/' + num + '.txt';
    
    document.slider.onerror = function () {
       // deal with the resource not loading here
    }
    document.slider.src = s;
    const desc = $("#description");
    desc.on("error" function () {
       // deal with the resource not loading here
    });
    desc.load(t);
    $("#num").text(num);

}
about 4 years ago · Juan Pablo Isaza Relatório

0

try this for the file exists or not

 function UrlExists(url)
 {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
 }

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

function loadFiles(num) {

    let s = 'assets/content/Compiladores/Slides/' + num + '.jpg';
    let t = 'assets/content/Compiladores/Texts/' + num + '.txt';
    
    document.slider.src = s;
    if(UrlExists(s)){
       $("#description").load(t);
    }
    if(UrlExists(t)){
       $("#num").text(num);
    }

}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda