Graham Wiggans
Graham Wiggans

Reputation: 31

Checking existance of a file on web server using server-side Javascript

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.

Upvotes: 2

Views: 1909

Answers (3)

Rahil Lakhani
Rahil Lakhani

Reputation: 408

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);
    });
});

Upvotes: 0

Graham Wiggans
Graham Wiggans

Reputation: 31

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>

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 99081

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

Upvotes: 3

Related Questions