如何获取Finder选择的文件的posix路径?

时间:2017-01-27 04:59:14

标签: javascript jxa

我正在尝试获取Finder选择的文件的完整路径。此时,我尝试了很多方法:

>> Application('Finder').selection()[0]
=> Application("Finder").startupDisk.folders.byName("Users").folders.byName("example").folders.byName("Tools").folders.byName("my-tools").documentFiles.byName("example.sh")
>>
>> Application('Finder').selection()[0].name()
=> "example.sh"
>>
>> Application('Finder').selection()[0].toString()
=> "[object ObjectSpecifier]"
>>
>> Application('Finder').selection()[0].posixPath()
!! Error on line 1: Error: Can't get object.
>>
>> Application('Finder').selection()[0].path()
!! Error on line 1: Error: Can't get object.
>>
>> Application('Finder').selection()[0].url()
=> "file:///Users/example/Tools/my-tools/example.sh"
>>
>> Path(Application('Finder').selection()[0])
!! Error on line 1: Error: Can't get object.
>>
>> Path(Application('Finder').selection()[0]).toString()
!! Error on line 1: Error: Can't get object.

这些命令都不会获得/Users/example/Tools/my-tools/example.sh的posix路径。

最终,我知道我可以简单地删除网址前面的file://

>> Application('Finder').selection()[0].url().replace(/^file:\/\//, '')
=> "/Users/example/Tools/my-tools/example.sh"

但这看起来很糟糕,似乎应该有一个命令来直接获取posix路径。

1 个答案:

答案 0 :(得分:1)

如果您检查the file's properties(),您会看到包含完整路径的唯一属性是url()。但是,在使用file://属性时,特殊字符将被转义并且网址以url()协议作为前缀:

>> Application('Finder').selection()[0].name()
=> "asdf\"asdf.txt"
>>
>> Application('Finder').selection()[0].url()
=> "file:///Users/example/Tools/my-tools/asdf%22asdf.txt"

为了获取POSIX路径,您可以unescape() url()并从file://的开头删除url()协议:

>> unescape(Application('Finder').selection()[0].url()).replace(/^file[:]\/\//, '')
=> "/Users/example/Tools/my-tools/asdf\"asdf.txt"