javascriptjsonadobe-indesignbasil.js

Check if file exists locally in Adobe Extendscript


I try to check for local files (.jpg) using a plain js loop. I get an error that, for example, file 5d3eb1905b243.jpg does not exists, but actually it does.

Also, I don't understand why the else statement ins't working and why 5d3eb1905b243.jpg isn't replaced with none.jpg.

Maybe the path is the problem?

Here's the code:

if (obj[i].hasOwnProperty('sharedimage_id')) {
  var imgFile = new File(
    '/Users/student/Desktop/seminar_robobooks/archiv/img/' +
      obj[i].sharedimage_id +
      '.jpg',
  );

  if (imgFile.exists) {
    noStroke(imgFile);
    image(obj[i].sharedimage_id + '.jpg', 56.5, 70.793, 69, 42);
  } else {
    noStroke(imgFile);
    image('none.jpg', 56.5, 70.793, 69, 42);
  }
}


Solution

  • You are not providing enough context to your question.

    1. Basil.js is a InDesign Javascript/Extendscript library for generative programming. Similar to Processing and P5.js
    2. Extendscript is a Adobe flavor of Javascript (Ecmascript 3) with some additions like File or XML
    3. We can't tell if the files on your filesystem exist or the Path is right

    Question: Which Basil version are you using? v2 (still in Beta)?

    Below is a little more boilerplate code to keep discussing and some pointers.

    1. the noStroke does not get an argument see this
    2. the file none.jpg needs to be in the data dir next to the InDesign Document you are executing against or you need to provide a absolute path See this
    3. See this tutorial on how to handle images
    var obj = [
      {
        sharedimage_id: '123456',
      },
      {
        sharedimage_id: '789012',
      },
    ];
    
    for (var i = 0; i < obj.length; i++) {
      // the File API test is part of Extendscript
      // https://www.indesignjs.de/extendscriptAPI/indesign10/#File.html
      var imgFile = new File('/absolute/path/to/' + obj[i].sharedimage_id + '.jpg');
    
      if (imgFile.exists === true) {
        // no stroke does not take an argument
        //https://basiljs2.netlify.com/reference/color/nostroke
        noStroke();
    
        image(obj[i].sharedimage_id + '.jpg', 56.5, 70.793, 69, 42);
      } else {
        noStroke();
        // the image needs also a path as the one above 
        // or should be in the data dir nest to the ID doc.
        // ID doc needs to be saved for that
        // https://basiljs2.netlify.com/reference/image/image
        image('none.jpg', 56.5, 70.793, 69, 42);
      }
    }
    

    P.S. I'm one of the authors and I'm linking to the current development version of the Reference. The links might break in the future.