You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Script Editor中创建可执行JS与Shell脚本的MacOS应用

在Script Editor中创建整合JS与Shell逻辑的Mac应用

问题背景

用Automator制作的Mac应用,先后执行一段JavaScript脚本和Shell脚本,但运行速度较慢。发现Script Editor编译的应用运行更快,希望在Script Editor里实现同样功能。

实现步骤

  1. 打开Script Editor(通过Launchpad或Spotlight搜索启动)
  2. 顶部工具栏的语言选择下拉菜单,选择JavaScript
  3. 替换默认代码为以下整合后的脚本(将原JS逻辑与Shell逻辑合并,减少执行开销):
function run(input) {
    const app = Application.currentApplication();
    app.includeStandardAdditions = true;

    const obsidianJsonFilePath = app.pathTo("home folder") + "/Library/Application Support/obsidian/obsidian.json";
    const vaults = JSON.parse(app.read(obsidianJsonFilePath)).vaults;

    let openInObsi = false;
    const pathArray = input.toString().split(",");
    const toOpen = [];
    pathArray.forEach(filePath => {
        const isFileInObsidianVault = Object.values(vaults).some(v => filePath.startsWith(v.path));
        if (isFileInObsidianVault && !filePath.includes("/.")) { // 排除.obsidian或.trash目录下的文件
            toOpen.push("obsidian://open?path=" + encodeURIComponent(filePath));
            openInObsi = true;
        } else {
            toOpen.push(filePath);
        }
    });

    // 执行原Shell脚本的打开逻辑
    if (openInObsi) {
        toOpen.forEach(item => {
            app.doShellScript(`open "${item.replace(/"/g, '\\"')}"`);
        });
    } else {
        const quotedPaths = toOpen.map(p => `"${p.replace(/"/g, '\\"')}"`).join(" ");
        app.doShellScript(`open -a "Obsidian" ${quotedPaths}`);
    }
}
  1. 测试脚本:点击顶部的运行按钮,可传入文件路径作为输入验证功能
  2. 导出为应用:点击菜单栏的「文件」->「导出」,格式选择应用程序,保存到指定位置即可

为什么更快?

Script Editor导出的应用直接运行脚本引擎,没有Automator的额外流程开销;同时将两段脚本的逻辑合并到单个JavaScript中,减少了进程间的通信步骤,进一步提升运行速度。

内容的提问来源于stack exchange,提问作者J W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:55:19