当你想从Tauri调用终端并运行类似 ls的命令的话,需要使用 @tauri-apps/api/shell的api,步骤如下

  1. 编辑 tauri.conf.json下的 tauri.allowlist.shell

    {
      "tauri": {
        "allowlist": {
          "shell": {
            "all": true, // enable all shell APIs
            "execute": true, // enable process spawn APIs
            "sidecar": true, // enable spawning sidecars
            "open": true // enable opening files/URLs using the default program
          }
        }
      }
    }
    

    其他api暂时不讨论,只说 execute,假设我们需要使用git命令(案例来自官网)

  2. 编辑 scope定义好需要用到的命令,要是没有定义则无法调用

    {
      "scope": [
        {
          "name": "run-git-commit",
          "cmd": "git",
          "args": ["commit", "-m", { "validator": "\\S+" }]
        }
      ]
    }
    
  3. 开始调用该命令

    import { Command } from '@tauri-apps/api/shell'
    const c = new Command('run-git-commit', ['commit', '-m', 'the commit message'])
    const std = await c.execute();
    std.stderr
    std.stdout
    std.code
    std.signal
    

    你可以将 args设置为 true来使js端可以传入任意参数

需要注意的是,我没有找到使用fs上定义的相对路径参数来在终端内使用的方式,所以目前只能使用一般的相对路径或绝对路径,比如 ./img.png和 E://img.png,但格式上需要注意。

对于我正在使用的win端来说, Command内访问路径只能使用 \单斜杠,不能 \\或 /,具体原因我也不清楚。

具体表现就是,当 console.log的时候,打印出来的是 \\,要是 \\\\的话原字符串才是 \\,打印出 \\代表是 \