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

时间:2015-02-27 19:54:12

标签: macos applescript osx-yosemite osascript javascript-automation

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

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

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

什么是JavaScript等价物?

7 个答案:

答案 0 :(得分:6)

没有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()

答案 1 :(得分:3)

这是的方式[注意:我不再推荐这种方法。参见编辑,下面]

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

答案 2 :(得分:3)

总结一下我现在正在做的事情,我正在回答我自己的问题。使用@ 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。另外,我正在声明我正在使用的变量以避免偶然的全局变量。

答案 3 :(得分:2)

使用已知道如何安全删除最后一个路径段的-[NSString stringByDeletingLastPathComponent]

ObjC.import('Foundation')

path = ObjC.unwrap($(path).stringByDeletingLastPathComponent)

或者,如果您更喜欢更危险的生命,可以使用正则表达式从POSIX路径字符串中去除最后一个路径段。在我的头顶(警告经纪人等):

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

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

答案 4 :(得分:2)

我想我找到了一种更简单的方法来获取父文件夹而不调用ObjC。

var app = Application.currentApplication();
app.includeStandardAdditions = true;
thePath = app.pathTo(this);

Path(thePath + '/../../')

答案 5 :(得分:1)

通过提供自包含的实用程序功能

来补充现有的有用答案
// 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 release notes

很容易概括这些功能,以提供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    
  }
}

答案 6 :(得分:0)

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

这是我的,不需要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
}