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.

JXA: Find My Purchased Music

A JXA (JavaScript for Automation) that analyzes your music library and shows which songs you own and which songs are Apple Music tracks
Continue reading

Last Light

Published on January 07, 2020

Southwest Georgia pines and sky

Published on January 07, 2020