Skip to content

文件 ​

ling.fs 照搬 Node 的 fs/promises:名字、参数、返回值都一样,会用 Node 就会用它。由 lingtools 执行,插件页面里直接调用。

权限 ​

路径读写
插件的数据目录、临时目录不需要不需要
用户在文件对话框里选的、随入口交给插件的、拖进页面的文件不需要不需要
其他路径fs.readfs

详见 权限。

常用示例 ​

ts
const fs = window.ling.fs
const dir = await window.ling.getPluginLocalDataPath()

// 读写文本
await fs.writeFile(`${dir}/notes.txt`, '你好')
const text = await fs.readFile(`${dir}/notes.txt`, 'utf8')

// 读写二进制(Uint8Array)
const bytes = await fs.readFile('/Users/me/photo.png')

// 列目录
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
  console.log(entry.name, entry.isDirectory())
}

// 是否存在
const exists = await fs.access(path).then(() => true, () => false)

// 元数据
const stat = await fs.stat(path)
console.log(stat.size, stat.mtime, stat.isFile())

// 创建目录、复制、移动、删除
await fs.mkdir(`${dir}/cache`, { recursive: true })
await fs.cp(src, dest, { recursive: true })
await fs.rename(oldPath, newPath)
await fs.rm(`${dir}/cache`, { recursive: true, force: true })

方法 ​

方法说明
access(path, mode?)检查存在与权限(fs.constants.F_OK / R_OK / W_OK / X_OK),不满足时 reject
readFile(path, options?)读整个文件;传 'utf8' 或 { encoding: 'utf8' } 得到字符串,否则得到 Uint8Array。大文件请用流
writeFile(path, data, options?)写整个文件(默认覆盖)
appendFile(path, data, options?)追加,不存在时创建
readdir(path, options?)列目录;withFileTypes: true 返回带类型的目录项;recursive: true 递归
stat(path) / lstat(path)元数据(lstat 不跟随软链接)
mkdir(path, options?)创建目录;recursive: true 创建上级目录且已存在不报错
mkdtemp(prefix)创建带随机后缀的目录
rm(path, options?)删除文件或(recursive: true)目录树。不进回收站、不确认,需要可恢复的删除用 shellTrashItem
rmdir(path)删除空目录
unlink(path)删除文件或链接
rename(oldPath, newPath)改名或移动(跨磁盘时失败,data.code 为 EXDEV)
copyFile(src, dest, mode?)复制文件
cp(src, dest, options?)复制文件或(recursive: true)目录树;不支持 filter
truncate(path, len?)截断
utimes(path, atime, mtime)设置访问与修改时间
chmod(path, mode)修改权限位(Windows 上只切换只读属性)
symlink(target, path, type?) / link(existing, newPath)创建软链接 / 硬链接
readlink(path) / realpath(path)软链接的目标 / 真实路径
open(path, flags?, mode?)打开文件,得到句柄
createReadStream(path, options?)读流(Web ReadableStream<Uint8Array>)
createWriteStream(path, options?)写流(Web WritableStream)
watch(path, options?)监听变化,返回异步迭代器
constants当前平台的常量

文件句柄 ​

ts
const handle = await fs.open(path, 'r')
try {
  const { bytesRead, buffer } = await handle.read({ length: 1024, position: 0 })
} finally {
  await handle.close()
}

句柄有 read、write、readFile、writeFile、appendFile、stat、truncate、sync、close、createReadStream、createWriteStream。用完请 close();页面重新加载、关闭或插件结束运行时会自动关闭。

流 ​

返回的是 Web Streams,不是 Node 的 Stream:

ts
// 逐块读大文件
const reader = fs.createReadStream(bigFile).getReader()
for (;;) {
  const { done, value } = await reader.read()
  if (done) break
  hash.update(value)
}

// 按文本逐行读
const lines = fs.createReadStream(logFile)
  .pipeThrough(new TextDecoderStream())

createReadStream 的选项:start、end(含)、highWaterMark(每块大小,默认 64 KiB)、signal。

监听 ​

ts
const controller = new AbortController()
for await (const event of fs.watch(dir, { recursive: true, signal: controller.signal })) {
  // event.eventType:'rename'(新建、删除、改名)或 'change'(内容变化)
  // event.filename:相对监听路径的路径
}

和 Node 一样不防抖,一次写入可能触发多条事件。退出循环、signal 中止或页面重新加载时停止监听。

错误 ​

失败时以 API 错误 reject,Node 的错误码放在 error.data.code:

ts
try {
  await fs.readFile(path, 'utf8')
} catch (error) {
  if (error.data?.code === 'ENOENT') { /* 文件不存在 */ }
}
情况codedata.code
没有权限读写这个路径(未声明 fs.read / fs)forbidden
不存在not_foundENOENT
系统拒绝访问permission_deniedEACCES / EPERM
已存在internalEEXIST

与 Node 的差异 ​

  • 全部异步,没有同步版本和回调版本。
  • 只支持 UTF-8 编码;不支持 bigint 选项。
  • 流是 Web Streams;不支持 cp 的 filter。
  • 路径按跟随软链接后的真实路径判断权限:插件目录里的软链接指向外部时,按外部路径检查。