使用 JXA AppleScript 获取活动 Finder 窗口的 POSIX 路径

Kym*_*mer 6 applescript finder javascript-automation macos-sierra

我想要这个 AppleScript 片段的 JXA 等效项:

tell application "Finder"

    # Get path
    set currentTarget to target of window 1
    set posixPath to (POSIX path of (currentTarget as alias))

    # Show dialog
    display dialog posixPath buttons {"OK"}

end tell
Run Code Online (Sandbox Code Playgroud)

我得到的最接近的是使用该url属性来初始化Foundation NSURL对象并访问其fileSystemRepresentation属性,如下所示:

// Get path
var finder = Application('Finder')
var currentTarget = finder.finderWindows[0].target()
var fileURLString = currentTarget.url()

// I'd like to get rid of this step
var fileURL = $.NSURL.alloc.initWithString(fileURLString)
var posixPath = fileURL.fileSystemRepresentation

// Show dialog
finder.includeStandardAdditions = true
finder.displayAlert('', {buttons: ['Ok'], message: posixPath})
Run Code Online (Sandbox Code Playgroud)

但这似乎不必要地复杂。有没有更好的方法可以在不使用 Foundation API或手动字符串整理的情况下访问 POSIX 路径?

系统事件 AppleScript 字典

如果我天真地尝试这个:

finder.finderWindows[0].target().posixPath()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

app.startupDisk.folders.byName("Users").folders.byName("kymer").folders.byName("Desktop").posixPath()
        --> Error -1728: Can't get object.
Run Code Online (Sandbox Code Playgroud)

这个答案似乎很相关,但我似乎无法调整它来满足我的需求:

App = Application.currentApplication()
App.includeStandardAdditions = true
SystemEvents = Application('System Events')

var pathToMe = App.pathTo(this)
var containerPOSIXPath = SystemEvents.files[pathToMe.toString()].container().posixPath()
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

JMi*_*lTX 2

@Kymer,你说:

但这似乎不必要地复杂。有没有更好的方法来访问 POSIX 路径而不使用 Cocoa API 或手动字符串整理?

你走在正确的轨道上。这是我所知道的最好的方法。如果有更好的,我也想了解一下。但是,这似乎运行得很快,并且适用于文件和文件夹。

var finderApp = Application("Finder");
var itemList  = finderApp.selection();
var oItem      = itemList[0];
var oItemPaths  = getPathInfo(oItem);

/* --- oItemPaths Object Keys ---
  oItemPaths.itemClass
  oItemPaths.fullPath
  oItemPaths.parentPath
  oItemPaths.itemName
*/

console.log(JSON.stringify(oItemPaths, undefined, 4))

function getPathInfo(pFinderItem) {

  var itemClass  = pFinderItem.class();  // returns "folder" if item is a folder.
  var itemURL = pFinderItem.url();
  var fullPath  = decodeURI(itemURL).slice(7);

  //--- Remove Trailing "/", if any, to handle folder item ---
  var pathElem  = fullPath.replace(/\/$/,"").split('/')

  var  itemName   = pathElem.pop();
  var parentPath = pathElem.join('/');

  return {
    itemClass:   itemClass,
    fullPath:    fullPath,
    parentPath:  parentPath,
    itemName:    itemName
    };

}
Run Code Online (Sandbox Code Playgroud)