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



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

POSIX path of ((path to me as text) & "::")

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

JavaScript的等价物是什么?

不包含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()

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

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

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

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

通过提供自包含的实用程序功能来补充现有的有用答案

// Return the POSIX path of the folder hosting this script / app.
// E.g., from within '/foo/bar.scpt', returns '/foo'.
function myPath() {
    var app = Application.currentApplication(); app.includeStandardAdditions = true
    return $(app.pathTo(this).toString()).stringByDeletingLastPathComponent.js
}
// Return the filename root (filename w/o extension) of this script / app.
// E.g., from within '/foo/bar.scpt', returns 'bar'.
// (Remove `.stringByDeletingPathExtension` if you want to retain the extension.)
function myName() {
    var app = Application.currentApplication(); app.includeStandardAdditions = true
    return $(app.pathTo(this).toString()).lastPathComponent.stringByDeletingPathExtension.js
}

注意:这些函数使用了ObjC桥的快捷语法形式$(...)表示ObjC.wrap().js表示ObjC.unwrap(),还利用了默认情况下Foundation框架的符号可用的事实-请参阅OS X 10.10 JXA发行说明。


很容易将这些函数概括为提供POSIX dirnamebasename实用程序的等价物:

// Returns the parent path of the specified filesystem path.
// A trailing '/' in the input path is ignored.
// Equivalent of the POSIX dirname utility.
// Examples:
//    dirname('/foo/bar') // -> '/foo'
//    dirname('/foo/bar/') // ditto
function dirname(path) {
  return $(path.toString()).stringByDeletingLastPathComponent.js
}
// Returns the filename component of the specified filesystem path.
// A trailing '/' in the input path is ignored.
// If the optional <extToStrip> is specified:
//   - If it it is a string, it is removed from the result, if it matches at
//     the end (case-sensitively) - do include the '.'
//   - Otherwise (Boolean or number), any truthy value causes any extension
//     (suffix) present to be removed.
// Equivalent of the POSIX basename utility; the truthy semantics of the
// 2nd argument are an extension.
// Examples:
//    basename('/foo/bar') // -> 'bar'
//    basename('/foo/bar/') // ditto
//    basename('/foo/bar.scpt', 1) // -> 'bar'
//    basename('/foo/bar.scpt', '.scpt') // -> 'bar'
//    basename('/foo/bar.jxa', '.scpt') // -> 'bar.jxa'
function basename(path, extToStrip) {
  path = path.toString()
  if (path[path.length-1] === '/') { path = path.slice(0, -1) }
  if (typeof extToStrip === 'string') {
    return path.slice(-extToStrip.length) === extToStrip ? $(path).lastPathComponent.js.slice(0, -extToStrip.length) : $(path).lastPathComponent.js    
  } else { // assumed to be numeric: if truthy, strip any extension
    return extToStrip ? $(path).lastPathComponent.stringByDeletingPathExtension.js : $(path).lastPathComponent.js    
  }
}

所以总结一下我现在所做的,我在回答我自己的问题。利用@foo和@CRGreen的出色回应,我得出了以下结论:

ObjC.import('Foundation');
var app, path, dir;
app = Application.currentApplication();
app.includeStandardAdditions = true;
path = app.pathTo(this);
dir = $.NSString.alloc.initWithUTF8String(path).stringByDeletingLastPathComponent.js + '/';

这与@CRGreen的回应非常接近,但它更简洁,我正在导入Foundation而不是Cocoa。另外,我声明了我正在使用的变量,以避免意外的全局变量。

使用-[NSString stringByDeletingLastPathComponent],它已经知道如何安全地删除最后一个路径段:

ObjC.import('Foundation')
path = ObjC.unwrap($(path).stringByDeletingLastPathComponent)

或者,如果您喜欢更危险的生活,可以使用正则表达式从POSIX路径字符串中剥离最后一个路径段。在我的脑海里(注意事项等):

path = path.replace(//[^/]+/*$/,'').replace(/^$/,'/')

(请注意,第二个replace()需要正确处理具有<2个部分的路径。)

我想我找到了一种更简单的方法,可以在不调用ObjC的情况下获得父文件夹。

var app = Application.currentApplication();
app.includeStandardAdditions = true;
thePath = app.pathTo(this);
Path(thePath + '/../../')

上面有很多有趣的解决方案。

这是我的,它不需要ObjC,并返回一个可能需要属性的对象。

'use strict';
var oScript = getScriptProp(this);
/*oScript Properties
    Path
    Name
    ParentPath
    Folder
*/
oScript.ParentPath;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function getScriptProp(pRefObject) {
  var app = Application.currentApplication()
  app.includeStandardAdditions = true
  var pathScript = app.pathTo(pRefObject).toString();
  var pathArr = pathScript.split("/")
  var oScript = {
    Path: pathScript,
    Name: pathArr[pathArr.length - 1],
    ParentPath: pathArr.slice(0, pathArr.length - 1).join("/"),
    Folder: pathArr[pathArr.length - 2]
  };
  return oScript
}

最新更新