2

I am generating HTML code using JavaScript on a web server and the HTML contains an object that has an id "ImageID" and a src parameter pointing to "Picture1.jpg".

I want to refresh the web page every 5 seconds and use Javascript to generate a new file path using incrementing numbers to say "Picture2.jpg" or "Picture3.jpg" but I want to use the Javascript to check whether such a new file name exists on the server before trying to refresh the img object using

document.getElementById("ImageID").src="Picture2.jpg";  

How can server-side JavaScript be used to test the existence of a particular server-side file?

Is these a simple FileExists() method or does the object returned by document.getElementById(ImageName) have to be queried somehow to find out if it successfully found the file or not.

Thanks everyone.

2
  • Is the image on the same server ? Commented Sep 30, 2015 at 18:28
  • What server side JavaScript environment are you using? Node.JS? Classic ASP? Something else? What API are you using to get a DOM in your server side JS? Commented Sep 30, 2015 at 18:33

3 Answers 3

3

You can check if a file exists on the same server using a XMLHttpRequest request and check if the response code is 200, i.e.:

<script>
    var http = new XMLHttpRequest();
    http.open('HEAD', "https://yourserver/file.jpg", false);
    http.send();
    console.log(http.status);
</script>

Note: You cannot query a remote server using XMLHttpRequest if cors isn't setup

Sign up to request clarification or add additional context in comments.

2 Comments

With the added benefit, in some browsers, that the request will cache the file (if you change it to a GET)
I'm using a Classic ASP server side JavaScript environment. The image is indeed on the same server.
1

Thanks to Pedro Lobito for supplying the answer. The code below worked for me.

<script TYPE="text/javascript">
function FileExists(FullFilePath) // Thanks to advice from Pedro Lobito

{         
    var http = new XMLHttpRequest(); // Best placed outside function
    http.open('HEAD', FullFilePath, false);
    http.send();  // This sets http.status to 200 if file exists (404 if not)
    return (http.status == 200);
}

// Example of call

TheFileExisis = FileExists("http://MyArea/MyWebHost.net/Images/Picture2.jpg");
</script>

Comments

0

I am using MOCHA CHAI for unit testing, and we have link which downloads PDF on click of button.

-----server.js

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
let userLang;

app.use(express.static('public'));

app.get('/files/:file(*)', (req, res, next) => {
    const file = req.params.file;
    const pathToFile = path.join(__dirname, '/files/', file);
    res.download(pathToFile, (err) => {
        if (!err) return; // file sent
        if (err && err.status !== 404) {
            next(err);
        }
        res.statusCode = 404;
        res.send('Cant find that file, sorry!');
    });
});

-----server.spec.js

import request from 'supertest';
const server = require('../../server/server');
describe('loading express', () => {
    let server;

    beforeEach(() => {
        server.start();
    });

    afterEach(() => {
        server.close();
    });

    it('should responds successfully to /', (done) => {
        request(server)
            .get('/')
            .expect(200, done);
    });


    it('should have download file', (done) => {
        request(server)
            .get('/files/XYZ.pdf')
            .expect(200, done);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.