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…
… it produces an privilege violation error.
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.currentApplication(), it works.
(“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.