host.fs
读写客户端文件、查询文件信息和遍历目录。
文件系统接口在所选客户端上读写文件、查询文件信息、遍历目录,以及创建和删除文件或目录。
下文的 host 是已选择的 RemoteHost,获取方式见主机发现。权限与通用错误见模块概览。
路径使用客户端操作系统的原生语法,相对路径以客户端启动目录为基准。所有方法均需要 fs.enabled;写入、创建和删除另需 fs.allow_write,见权限。
host.fs.readFile(path)
功能: 完整读取文件的原始字节。
参数: path: string 必填,文件路径。
返回值: Promise<Uint8Array>。完整文件会占用相应 JavaScript 内存。
host.fs.readTextFile(path)
功能: 完整读取文件并按 UTF-8 解码;非法序列替换为替代字符。
参数: path: string 必填,文件路径。
返回值: Promise<string>。
host.fs.readDir(path)
功能: 按需逐条读取目录。
参数: path: string 必填,目录路径。
返回值: AsyncIterableIterator<DirEntry>,不是 Promise。每项含 name: string 和布尔字段 isFile、isDirectory、isSymlink。首次 next() 才打开目录,迭代结束、调用 return() 或 break 会释放游标。
host.fs.stat(path)
功能: 获取文件或目录的信息,跟随允许访问的符号链接。
参数: path: string 必填。
返回值: Promise<FileInfo>,包含:
| 字段 | 类型 | 说明 |
|---|---|---|
isFile、isDirectory、isSymlink | boolean | 文件类型信息 |
size | number | 字节大小 |
mtime、atime、birthtime | Date / null | 修改、访问、创建时间;不可用时为 null |
host.fs.writeFile(path, data, options?)
功能: 将字节写入文件。写入分块立即生效,后续失败不会回滚已写内容。
参数: path: string、data: Uint8Array 必填;options?: WriteOptions 如下。不会自动创建父目录。
| 字段 | 类型 | 默认值与说明 |
|---|---|---|
create | boolean | true;为 false 时要求文件已存在 |
append | boolean | false;默认截断旧文件,为 true 时追加 |
返回值: Promise<void>。
host.fs.writeTextFile(path, data, options?)
功能: 将字符串编码为 UTF-8 后写入文件。
参数: path: string、data: string 必填;options?: WriteOptions 与 writeFile() 相同。
返回值: Promise<void>,写入和失败规则与 writeFile() 相同。
host.fs.mkdir(path, options?)
功能: 创建目录。
参数: path: string 必填;options?: { recursive?: boolean },默认 recursive: false,为 true 时创建缺失的父目录。
返回值: Promise<void>。
host.fs.remove(path, options?)
功能: 删除文件或目录。
参数: path: string 必填;options?: { recursive?: boolean },默认 recursive: false。删除非空目录需启用递归。
返回值: Promise<void>。
类型声明见 remote.d.ts。
