Jump to content

Default Icon when path does not match


Recommended Posts

I am iterating over an array, and within my map method, I want to check if the icon file exists (because it is okay if they don't). However, I cannot get this file checking to work. I also tried most other file existence methods: https://byby.dev/node-check-if-file-exists

 

.map((element) => {
  let iconPath = 'icon.png';
  // Check if the file or path exists
  if (fs.existsSync(iconPath)) {
    iconPath = `${__dirname}/simple-icons/${element.name.toLowerCase()}.svg`;
  }

  return {
    title: `${element.display} (${element.name}) [${element.key}]`,
    subtitle: `${element.address.name}, ${element.address.line1}, ${element.address.line2}, ${element.address.contacts}, ${element.address.country}`,
    arg: element.key,
    icon: { path: iconPath },
    autocomplete: element.key,
    valid: false,
  };
  });

 

 

Is there maybe something already implemented to use a fallback icon, if the path has no target?

Link to comment

But I want to conditionally overwrite icon.png with an icon that exists. If I delete icon: { path: iconPath }, I would have no chance to show custom-icon.png

 

For example, right now my results look like this:

image.thumb.png.d1600b828d2907f8da5b974ef4fd6d96.png

 

Since I only got the tesla icon in: simple-icons/tesla.svg (see if condition above), I see the tesla icon, however the other icons should have the icon.png

Link to comment

Your code looks reversed. What you seem to be doing is setting a default icon which will always exist, then saying “if icon.png exists (which it will) replace it with something else”.


What you should do is set the alternative icon first, and if that does not exist, use icon.png. Something like (untested):

 

const elementIcon = `${__dirname}/simple-icons/${element.name.toLowerCase()}.svg`
const iconPath = fs.existsSync(elementIcon) ? elementIcon : "icon.png"

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...