JXA: How to use openForAccess

Apple’s documentation shows that to open a file for writing in a JXA script, you call the openForAccess method on an Application instance. What the documentation doesn’t make clear is that you must call openForAccess on the instance returned by Application.currentApplication(). Anything else will fail.

If you run this code in Script Editor…

let app = Application('Finder');
app.includeStandardAdditions = true;
let desktop = app.pathTo('desktop').toString();
let myFile = `${desktop}/temp.txt`;
let openedFile = app.openForAccess(Path(myFile), { writePermission: true });
app.closeAccess(openedFile);

… it produces an privilege violation error.

  Script Editor error message

Script Editor even helpfully tells you that the privilege violation occurred on the line where we attempted to open the file.

But if you change Application('Finder') to Application.currentApplication(), it works.

let app = Application.currentApplication();
app.includeStandardAdditions = true;
let desktop = app.pathTo('desktop').toString();
let myFile = `${desktop}/temp.txt`;
let openedFile = app.openForAccess(Path(myFile), { writePermission: true });
app.closeAccess(openedFile);
  Script Editor no error message

(“Undefined” simply means the last statement didn’t return a value.)

If you need to open a file for writing, you must set a variable to Application.currentApplication() and call openForAccess on that Application instance — even if you’re already working with another application.

Previous PostNext Post
Previous PostNext Post