Skip to content

运行本地程序 ​

ling.spawn 在插件页面里直接运行本机程序,接口对齐 Node 的 child_process(spawn / exec / execFile / fork)。需要 spawn 权限。

高风险权限

spawn 能运行任意程序,相当于以用户的身份完全控制电脑;lingtools 不检查命令和路径。插件市场会把它标为高风险,用户可以单独关闭。只在确实需要时申请,并且不要把用户输入直接拼进命令行。

只能在插件主页面和自建窗口里调用。

exec:执行一条命令拿输出 ​

ts
const { stdout } = await window.ling.spawn.exec('git rev-parse --abbrev-ref HEAD', {
  cwd: projectDir,
})

经 shell 执行(macOS /bin/sh -c,Windows cmd.exe /d /s /c),结束后一次给出输出。命令字符串由你负责转义。

execFile:不经 shell 执行 ​

ts
const { stdout } = await window.ling.spawn.execFile('/usr/bin/sw_vers', ['-productVersion'])

参数作为数组传递,不经 shell,不需要转义,更安全。能用 execFile 就不要用 exec。

两者的选项:

选项说明
cwd工作目录(绝对路径),默认为用户主目录
env环境变量,叠加在 lingtools 的环境上;值为 null 时删除该变量
encoding输出编码,默认 'utf8';'buffer' 时输出为 Uint8Array
maxBufferstdout、stderr 各自的上限,默认 1 MiB,最大 16 MiB
timeout超时毫秒数,超时以 timeout 失败
signalAbortSignal,触发时结束进程
windowsHideWindows 上不显示控制台窗口,默认 true

返回值可以 await,另有 kill()。没有标准输入(读 stdin 的命令会立即读到结束)。

失败时以 spawn_failed reject,error.data:

  • { kind: 'start', code: 'ENOENT', … }:程序没能启动(如找不到命令);
  • { kind: 'exit', exitCode, signal, stdout, stderr }:非零退出或被信号结束;
  • { kind: 'maxBuffer', … }:输出超过上限。

spawn:长时间运行、流式输出 ​

ts
const child = window.ling.spawn('ping', ['-c', '4', 'example.com'])
child.stdout?.setEncoding('utf8')
child.stdout?.on('data', (chunk) => append(chunk))
child.on('close', (code) => console.log('退出码', code))
child.on('error', (error) => console.error(error))

返回的 ChildProcess 与 Node 相同:pid、exitCode、stdin(write / end)、stdout / stderr(on('data')、setEncoding、pause / resume)、kill(signal?),以及事件 spawn、exit、close、error。

额外的选项:

选项说明
stdio'pipe'(默认)或 'ignore',可以分别设置 [stdin, stdout, stderr]
shell经 shell 运行
detached分离:插件和 lingtools 退出时不结束它
independentlingtools 扩展:完全独立启动,进程不再是 lingtools 的子进程。要求同时 detached: true 且 stdio: 'ignore'

打开 GUI 程序(如用指定浏览器打开网址),用分离 + 独立启动,否则程序会随插件一起被关闭:

ts
window.ling.spawn('/Applications/Firefox.app/Contents/MacOS/firefox', [url], {
  detached: true,
  independent: true,
  stdio: 'ignore',
})

fork:运行一个 Node 脚本 ​

ts
const child = window.ling.spawn.fork(`${pluginDir}/worker.cjs`, ['--fast'])
child.on('message', (msg) => console.log('收到', msg))
child.send({ task: 'start' })

用 lingtools 的 Node 运行时运行一个 JS 模块,带 IPC 通道(脚本里用 process.send / process.on('message'))。本机还没有 Node 时会先弹窗下载。被运行的脚本里没有 ling。消息必须能 JSON 序列化。

需要长期运行的 Node 逻辑,更常见的做法是 Node 后端。

生命周期 ​

  • 非分离的子进程属于启动它的页面:页面重新加载、关闭或插件结束时,子进程(连同它派生的进程)会被结束。
  • 每个插件同时运行的进程数有上限,超出时以 too_many_processes 失败。
  • 进程继承 lingtools 的环境变量。macOS 上从访达启动 lingtools 时,PATH 可能不含 Homebrew 等目录,调用命令时写绝对路径,或通过 env 补充 PATH。

与 Node 的差异 ​

  • 没有同步版本(spawnSync、execSync 等)。
  • 默认工作目录是用户主目录;env 是叠加而不是替换。
  • Windows 上默认隐藏控制台窗口;任何信号都等同强制结束。
  • stdio 不支持数字、流对象和 'ipc';'inherit' 等同 'ignore'。
  • 没有 'data' 监听者时输出直接丢弃,不会让子进程卡住。