How To: Test image exists

Brass Contributor

I need to test to see if an image exists in a library. I am basing my code on the PNP JS documentation found here: https://pnp.github.io/pnpjs/sp/files/

 

This code works

const file = sp.web.getFileByUrl(url);

but it always returns an object. My challenge had been, how to tell if the object is indicating the image exists or doesn't. The only thing that has worked for me is to call the getItem() then fieldValuesAsText().

 

sp.web.getFileByUrl("").getItem().then(function(val){
    val.fieldValuesAsText()
});
 
When I console.log() the output, I get yet another object that allows me to see that a non-exist image is returning a 404 error but the properties are [[]] and I can't address them individually in code.
 
1 Reply
Hi, If you are aware of the extension of the file, try to use the getText or other methods on the file object. You can also check the file object to see whether the file exists or not.