如何在JavaScript for Automation中获取当前脚本文件夹的POSIX路径?

aar*_*nk6 4 macos applescript osascript osx-yosemite javascript-automation

在AppleScript中,可以使用此行获取当前脚本所在的文件夹的POSIX路径:

POSIX path of ((path to me as text) & "::")
Run Code Online (Sandbox Code Playgroud)

结果示例: /Users/aaron/Git/test/

什么是JavaScript等效项?

Put*_*tin 7

不涉及ObjC的纯JXA代码:

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)


CRG*_*een 5

这是一种方法[注意:我不再推荐这种方法。请参见下方的“编辑”

app = Application.currentApplication();
app.includeStandardAdditions = true;
path = app.pathTo(this);
app.doShellScript('dirname \'' + path + '\'') + '/';
Run Code Online (Sandbox Code Playgroud)

请注意path在doShellScript中使用单引号引起来的空格等路径

编辑 由于使用了不安全的路径引用方法而被@foo拍了一下之后,我想用以下方法修改此答案:

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 + "/";
Run Code Online (Sandbox Code Playgroud)

当然,如果要使用此字符串,则仍然必须处理它是否包含可疑字符。但是至少在现阶段这不是问题。这还演示了JXA用户可用的一些概念,例如使用ObjC桥以及.js将字符串“强制”转换为JavaScript字符串(来自NSString)。

  • “注意路径周围的单引号以使用带空格的路径” ...如果路径字符串包含单引号,则会完全炸毁。_Never_不会生成代码而不会_fully_清理您的输入内容:这是完全不安全的。使用`do shell script`时,请始终使用函数quotedForm(s){返回“'” + s.replace(“'”,“'\\”“)+”'“}}正确地单引号连接之前,可以输入任意文本,例如`app.doShellScript('dirname'+ quotedForm(path))`。 (3认同)