如何在 JavaScript for Automation 中获取当前脚本文件夹的 POSIX 路径? [英] How to get POSIX path of the current script's folder in JavaScript for Automation?

查看:23
本文介绍了如何在 JavaScript for Automation 中获取当前脚本文件夹的 POSIX 路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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) & "::")

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

JavaScript 的等价物是什么?

What’s the JavaScript equivalent?

推荐答案

这是一种方法[注意:我不再推荐这种方法.请参阅下面的编辑]:

app = Application.currentApplication();
app.includeStandardAdditions = true;
path = app.pathTo(this);
app.doShellScript('dirname \'' + path + '\'') + '/';

注意 path 周围的单引号,以便在 doShellScript 中处理带有空格等的路径

note the single quotes surrounding path to work with paths with spaces, etc., in the doShellScript

编辑在被@foo 掌掴使用相当不安全的路径引用方法后,我想修改这个答案:

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 + "/";

当然,如果你要使用这个字符串,你仍然需要处理它是否包含有问题的字符.但至少在现阶段这不是问题.这也演示了 JXA 用户可用的一些概念,例如使用 ObjC 桥和 .js 将字符串强制"为 JavaScript 字符串(来自 NSString).

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).

这篇关于如何在 JavaScript for Automation 中获取当前脚本文件夹的 POSIX 路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆