Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: Image is not defined

I am trying to make a website, in which I include images via links. If an image is non-existent, or just 1 pixel wide, the website should display an alternative image. I am using Jade/Pug and JS.

I try to make a list of links beforehand, before rendering them on the website. That way I can just iterate threw my link-list in the .pug file afterwards. So what I am trying to do is, to check, if an image has a certain size, using JS only. If it does, I add the link to my list, if not, then I add an alternative link.

This is the important part of my code in the app.js-file:

app.get("/", function (req, res) {
    //get all the books
    var isbns = [];
    var links = [];
    dbClient.query("SELECT isbn FROM book WHERE id < 20", function (dbError, dbItemsResponse){
        isbns = dbItemsResponse.rows;
        var linkk = 0;
        for(i=0;i<20;i++){
            linkk = "http://covers.openlibrary.org/b/isbn/" + Object.values(isbns[i]) + "-M.jpg";
            var wid = getMeta(linkk);
               if(wid < 2){
                    links[i]="https://i.ibb.co/7JnVtcB/NoCover.png";
                } else {
                    links[i]=linkk;
                }
            }

    });
});

function getMeta(url){   
    var img = new Image(); //or document.createElement("img");
    img.onload = function(){
        alert(this.width);
    };
    img.src = url;
}

This gives me a ReferenceError: Image() is not defined. If I try to use document.createElement("img"); it says "document is not defined". How can i check on the server-side if an Image is existent? Or how can I use the Image-Constructor in my app.js file? Without using my Jade/Pug/HTML file in any way. Sorry If it's a dumb question, but I am trying to figure this out since 20 hours non-stop, and I can't get it to work.

like image 311
Firefighter123 Avatar asked Nov 15 '25 11:11

Firefighter123


1 Answers

You are mixing up nodejs and javascript. Your code is nodejs and therefor on the sererside. window and Image are only available in the browser, resp. on the client side.

For checking if a file exists, (Only on the serverside!=) you can use fs => fs.access.

const fs = require('fs')

// Check if the file exists
fs.access(file, fs.constants.F_OK, err => {
  console.log(file, err ? 'does not exist' : 'exists')
})

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!