# 运行程序、文件与网络

> 插件可用的 NSH 标准模块接口：process.run / spawn 运行本机程序，fs/promises 读写文件，fetch 访问网络，以及各自需要声明的权限和错误码。

- 网页：https://dinox.info/guides/atomd-plugins/modules
- 本页 Markdown：https://dinox.info/guides/atomd-plugins/modules.md
- 全部文档索引：https://dinox.info/llms.txt

除了 [Host API](https://dinox.info/guides/atomd-plugins/host-api.md)，插件还可以用 NSH 的标准模块做三类事：运行本机程序、读写文件、访问网络。每一类都要在 `nsh.json` 里声明对应权限，见 [权限与沙箱](https://dinox.info/guides/atomd-plugins/capabilities.md)。

这些模块和 Node.js 的同名模块**相似但不相同**，以本页为准。

## process：运行程序

```ts
import process from "process";
```

### process.run(command, args?, options?)

运行一个程序，等它结束，返回全部输出。适合一次性的命令。

```ts
const out = await process.run("git", ["log", "-1", "--format=%s"], { timeoutMs: 5000 });
// { code: 0, signal: null, stdout: "…", stderr: "" }
```

| 参数                  | 说明                                                                     |
| ------------------- | ---------------------------------------------------------------------- |
| `command`           | 程序名，必须列在 `capabilities.process.execute` 里。**不经过 shell**，管道、重定向、通配符都不可用 |
| `args`              | 参数数组                                                                   |
| `options.cwd`       | 工作目录，必须在 `capabilities.fs.write` 的范围内。默认是插件的数据目录                       |
| `options.timeoutMs` | 超时后结束整个进程树。默认 30 秒                                                     |

返回 `{ code, signal, stdout, stderr }`。每个输出流最多保留 8 MB。

### process.spawn(command, args?, options?)

启动一个长期运行的程序，以流的方式读取输出。适合对话式的命令行工具、语言服务器等。

```ts
const child = process.spawn("codex", ["app-server"], { lines: true, stdin: "pipe" });

child.on("stdout", (line) => handle(JSON.parse(line)));
child.on("stderr", (line) => console.warn(line));
child.on("exit", ({ code, signal, error }) => console.log("exited", code, error));

child.write(JSON.stringify({ method: "initialize" }) + "\n");
```

| 选项                | 说明                                              |
| ----------------- | ----------------------------------------------- |
| `cwd`、`timeoutMs` | 同 `run`。`spawn` 默认没有超时                          |
| `stdin`           | `"pipe"` 时可以用 `write` / `end` 写入标准输入，否则标准输入是关闭的 |
| `lines`           | `true` 时按行回调（去掉换行符），否则按块回调                      |

返回的 `ChildProcess`：

| 成员                                      | 说明                                                 |
| --------------------------------------- | -------------------------------------------------- |
| `pid`                                   | 进程 ID                                              |
| `on("stdout" \| "stderr", (text) => …)` | 输出                                                 |
| `on("exit", (result) => …)`             | 结束，`result` 是 `{ code, signal, error, errorCode }` |
| `write(text)`                           | 写入标准输入，最多积压 1 MB                                   |
| `end()`                                 | 关闭标准输入                                             |
| `kill()`                                | 结束整个进程树                                            |

插件被关闭或 Reload 时，atomd 会停掉它的虚拟机，它启动的子进程也随之结束。

### 环境变量与其他

| 成员                 | 说明                                                                |
| ------------------ | ----------------------------------------------------------------- |
| `process.env`      | 插件能读到的环境变量：基础变量加上 `capabilities.process.env` 里声明的                 |
| `process.dataDir`  | 插件自己的数据目录，即 atomd 数据目录下的 `plugin-data/<id>/`                      |
| `process.platform` | `"macos"`、`"windows"`、`"linux"`（注意不是 Node 的 `"darwin"`、`"win32"`） |
| `process.arch`     | `"aarch64"`、`"x86_64"`                                            |

子进程只拿到 `PATH`、`HOME`、`TMPDIR`、`LANG` 等基础变量，加上 `process.env` 里声明的。其他变量（比如 `OPENAI_API_KEY`）必须声明才会传过去：

```json title="nsh.json"
"process": {
  "execute": ["codex"],
  "env": ["OPENAI_API_KEY", "HTTPS_PROXY"]
}
```

## fs/promises：读写文件

```ts
import { readFile, writeFile, mkdir, readdir, exists, stat, rename, unlink, rmdir } from "fs/promises";

const dir = process.dataDir!;
await mkdir(`${dir}/cache`, { recursive: true });
await writeFile(`${dir}/cache/index.json`, JSON.stringify(index));
const text = await readFile(`${dir}/cache/index.json`, "utf8");
```

| 函数                                              | 说明                   |
| ----------------------------------------------- | -------------------- |
| `readFile(path)` / `readFile(path, "utf8")`     | 读成 `Uint8Array` 或字符串 |
| `writeFile(path, data)`                         | 写入字符串或 `Uint8Array`  |
| `readdir(path, { withFileTypes? })`             | 列出目录                 |
| `mkdir(path, { recursive? })`                   | 创建目录                 |
| `exists(path)`、`stat(path)`、`lstat(path)`       | 查询                   |
| `rename(from, to)`、`unlink(path)`、`rmdir(path)` | 移动、删除                |

路径必须落在声明的范围内，读需要 `fs.read`，写需要 `fs.write`：

```json title="nsh.json"
"fs": {
  "read": ["${dataDir}"],
  "write": ["${dataDir}"]
}
```

`${dataDir}` 是插件数据目录，`${pluginDir}` 是插件安装目录。

> **注意**
> 不要用 `fs.write` 修改用户的笔记。改笔记请用 [`atomd.note.applyEdits`](/guides/atomd-plugins/host-api#atomdnoteapplyedits)：它能撤销，不会和编辑器里未保存的内容冲突。直接写笔记文件的插件不会通过审核。

## fetch：访问网络

全局的 `fetch` 和浏览器的用法一样：

```ts
const res = await fetch("https://api.example.com/v1/summarize", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ text: note.markdown }),
});
const data = await res.json();
```

每个请求（包括重定向后的地址）都要在 `capabilities.network` 里有授权：

```json title="nsh.json"
"network": {
  "hosts": ["api.example.com"],
  "http": [{ "host": "quotes.example.com", "methods": ["GET"], "pathPrefix": "/v1/" }]
}
```

| 键       | 说明                                                         |
| ------- | ---------------------------------------------------------- |
| `hosts` | 可以用任意方法访问的域名。`*.example.com` 匹配子域名                         |
| `http`  | 更细的授权：`host`，以及可选的 `methods`、`schemes`、`port`、`pathPrefix` |

审核时只接受具体的域名，见 [审核规范](https://dinox.info/guides/atomd-plugins/review.md)。WebSocket 按同一地址的 GET 请求检查。

## 错误码

这些调用失败时，错误对象带 `code`：

| `code`                              | 原因                                                           |
| ----------------------------------- | ------------------------------------------------------------ |
| `ERR_ACCESS_DENIED`                 | 没有声明对应权限，或 atomd 没有授予。错误对象的 `permission` 和 `resource` 说明缺哪一项 |
| `ENOENT`                            | 程序或文件不存在（例如用户没装 `codex`）。请在界面上提示用户怎样安装                       |
| `ETIMEDOUT`                         | 超过 `timeoutMs`                                               |
| `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` | `run` 的输出超过 8 MB，改用 `spawn`                                  |
| `ERR_NSH_QUOTA_EXCEEDED`            | `write` 积压超过 1 MB                                            |

```ts
try {
  await process.run("pandoc", ["--version"]);
} catch (e: any) {
  if (e.code === "ENOENT") notify("请先安装 pandoc：brew install pandoc");
  else throw e;
}
```