读取文件 (Bun.file())
Bun.file(path): BunFile
使用 Bun.file(path) 函数创建一个 BunFile 实例。一个 BunFile 代表一个延迟加载的文件;初始化它并不会真正从磁盘读取文件。
Blob 接口,因此可以以各种格式读取内容。
file:// URL 创建。
BunFile 可以指向磁盘上不存在文件的位置。
text/plain;charset=utf-8,但可以通过向 Bun.file 传递第二个参数来覆盖。
stdin、stdout 和 stderr 暴露为 BunFile 的实例。
删除文件 (file.delete())
您可以通过调用 .delete() 函数来删除文件。
写入文件 (Bun.write())
Bun.write(destination, data): Promise<number>
Bun.write 函数是一个多功能工具,用于将各种负载写入磁盘。
第一个参数是 destination,可以是以下类型之一:
string: 文件系统上位置的路径。使用"path"模块来操作路径。URL: 一个file://描述符。BunFile: 一个文件引用。
stringBlob(包括BunFile)ArrayBuffer或SharedArrayBufferTypedArray(Uint8Array等)Response
查看系统调用
查看系统调用
| 输出 | 输入 | 系统调用 | 平台 |
|---|---|---|---|
| file | file | copy_file_range | Linux |
| file | pipe | sendfile | Linux |
| pipe | pipe | splice | Linux |
| terminal | file | sendfile | Linux |
| terminal | terminal | sendfile | Linux |
| socket | file 或 pipe | sendfile (如果是 http,非 https) | Linux |
| file (不存在) | file (path) | clonefile | macOS |
| file (存在) | file | fcopyfile | macOS |
| file | Blob 或 string | write | macOS |
| file | Blob 或 string | write | Linux |
stdout:
使用 FileSink 增量写入
Bun 提供了一个称为 FileSink 的原生增量文件写入 API。要从 BunFile 检索 FileSink 实例:
.write()。
.flush()。这将返回刷新的字节数。
FileSink 的_高水位标记_达到时,缓冲区也将自动刷新;也就是说,当其内部缓冲区满时。这个值是可以配置的。
bun 进程将保持活动状态,直到此 FileSink 通过 .end() 显式关闭。要选择退出此行为,您可以”取消引用”实例。
目录
Bun 的node:fs 实现是快速的,我们尚未实现专门用于读取目录的 Bun 特定 API。目前,您应该在 Bun 中使用 node:fs 来处理目录。
读取目录 (readdir)
要在 Bun 中读取目录,请使用node:fs 中的 readdir。
递归读取目录
要在 Bun 中递归读取目录,请使用带有recursive: true 的 readdir。
创建目录 (mkdir)
要递归创建目录,请使用node:fs 中的 mkdir:
基准测试
以下是 Linuxcat 命令的 3 行实现。
terminal
cat 快 2 倍。
