How to get POSIX path of the current script's folder in JavaScript for Automation?
applescript, javascript-automation, macos, osascript, osx-yosemite
Solution
Here's a way [NOTE: I NO LONGER RECOMMEND THIS METHOD. SEE EDIT, BELOW]:
app = Application.currentApplication();
app.includeStandardAdditions = true;
path = app.pathTo(this);
app.doShellScript('dirname \'' + path + '\'') + '/';
note the single quotes surrounding `path` to work with paths with spaces, etc., in the doShellScript
EDIT After being slapped on the hand by @foo for using a fairly unsafe path-quoting method, I'd like to amend this answer with:
ObjC.import("Cocoa");
app = Application.currentApplication();
app.includeStandardAdditions = true;
thePath = app.pathTo(this);
thePathStr = $.NSString.alloc.init;
thePathStr = $.NSString.alloc.initWithUTF8String(thePath);
thePathStrDir = (thePathStr.stringByDeletingLastPathComponent);
thePathStrDir.js + "/";
If you're going to use this string, of course, you still have to deal with whether or not it has questionable characters in it. But at least at this stage this is not an issue. This also demonstrates a few concepts available to the JXA user, like using the ObjC bridge and `.js` to get the string "coerced" to a JavaScript string (from NSString).
Problem
In AppleScript it’s possible to get the the POSIX path of the folder the current script is located in using this line: ``` POSIX path of ((path to me as text) & "::") ``` Example result: `/Users/aaron/Git/test/` What’s the JavaScript equivalent?