Node.js v25.0.0 文档
- Node.js v25.0.0
-
目录
- 文件系统
- Promise 示例
- 回调示例
- 同步示例
- Promises API
- 类:
FileHandle
- 事件:
'close'
filehandle.appendFile(data[, options])
filehandle.chmod(mode)
filehandle.chown(uid, gid)
filehandle.close()
filehandle.createReadStream([options])
filehandle.createWriteStream([options])
filehandle.datasync()
filehandle.fd
filehandle.read(buffer, offset, length, position)
filehandle.read([options])
filehandle.read(buffer[, options])
filehandle.readableWebStream([options])
filehandle.readFile(options)
filehandle.readLines([options])
filehandle.readv(buffers[, position])
filehandle.stat([options])
filehandle.sync()
filehandle.truncate(len)
filehandle.utimes(atime, mtime)
filehandle.write(buffer, offset[, length[, position]])
filehandle.write(buffer[, options])
filehandle.write(string[, position[, encoding]])
filehandle.writeFile(data, options)
filehandle.writev(buffers[, position])
filehandle[Symbol.asyncDispose]()
- 事件:
fsPromises.access(path[, mode])
fsPromises.appendFile(path, data[, options])
fsPromises.chmod(path, mode)
fsPromises.chown(path, uid, gid)
fsPromises.copyFile(src, dest[, mode])
fsPromises.cp(src, dest[, options])
fsPromises.glob(pattern[, options])
fsPromises.lchmod(path, mode)
fsPromises.lchown(path, uid, gid)
fsPromises.lutimes(path, atime, mtime)
fsPromises.link(existingPath, newPath)
fsPromises.lstat(path[, options])
fsPromises.mkdir(path[, options])
fsPromises.mkdtemp(prefix[, options])
fsPromises.mkdtempDisposable(prefix[, options])
fsPromises.open(path, flags[, mode])
fsPromises.opendir(path[, options])
fsPromises.readdir(path[, options])
fsPromises.readFile(path[, options])
fsPromises.readlink(path[, options])
fsPromises.realpath(path[, options])
fsPromises.rename(oldPath, newPath)
fsPromises.rmdir(path[, options])
fsPromises.rm(path[, options])
fsPromises.stat(path[, options])
fsPromises.statfs(path[, options])
fsPromises.symlink(target, path[, type])
fsPromises.truncate(path[, len])
fsPromises.unlink(path)
fsPromises.utimes(path, atime, mtime)
fsPromises.watch(filename[, options])
fsPromises.writeFile(file, data[, options])
fsPromises.constants
- 类:
- 回调 API
fs.access(path[, mode], callback)
fs.appendFile(path, data[, options], callback)
fs.chmod(path, mode, callback)
fs.chown(path, uid, gid, callback)
fs.close(fd[, callback])
fs.copyFile(src, dest[, mode], callback)
fs.cp(src, dest[, options], callback)
fs.createReadStream(path[, options])
fs.createWriteStream(path[, options])
fs.exists(path, callback)
fs.fchmod(fd, mode, callback)
fs.fchown(fd, uid, gid, callback)
fs.fdatasync(fd, callback)
fs.fstat(fd[, options], callback)
fs.fsync(fd, callback)
fs.ftruncate(fd[, len], callback)
fs.futimes(fd, atime, mtime, callback)
fs.glob(pattern[, options], callback)
fs.lchmod(path, mode, callback)
fs.lchown(path, uid, gid, callback)
fs.lutimes(path, atime, mtime, callback)
fs.link(existingPath, newPath, callback)
fs.lstat(path[, options], callback)
fs.mkdir(path[, options], callback)
fs.mkdtemp(prefix[, options], callback)
fs.open(path[, flags[, mode]], callback)
fs.openAsBlob(path[, options])
fs.opendir(path[, options], callback)
fs.read(fd, buffer, offset, length, position, callback)
fs.read(fd[, options], callback)
fs.read(fd, buffer[, options], callback)
fs.readdir(path[, options], callback)
fs.readFile(path[, options], callback)
fs.readlink(path[, options], callback)
fs.readv(fd, buffers[, position], callback)
fs.realpath(path[, options], callback)
fs.realpath.native(path[, options], callback)
fs.rename(oldPath, newPath, callback)
fs.rmdir(path[, options], callback)
fs.rm(path[, options], callback)
fs.stat(path[, options], callback)
fs.statfs(path[, options], callback)
fs.symlink(target, path[, type], callback)
fs.truncate(path[, len], callback)
fs.unlink(path, callback)
fs.unwatchFile(filename[, listener])
fs.utimes(path, atime, mtime, callback)
fs.watch(filename[, options][, listener])
fs.watchFile(filename[, options], listener)
fs.write(fd, buffer, offset[, length[, position]], callback)
fs.write(fd, buffer[, options], callback)
fs.write(fd, string[, position[, encoding]], callback)
fs.writeFile(file, data[, options], callback)
fs.writev(fd, buffers[, position], callback)
- 同步 API
fs.accessSync(path[, mode])
fs.appendFileSync(path, data[, options])
fs.chmodSync(path, mode)
fs.chownSync(path, uid, gid)
fs.closeSync(fd)
fs.copyFileSync(src, dest[, mode])
fs.cpSync(src, dest[, options])
fs.existsSync(path)
fs.fchmodSync(fd, mode)
fs.fchownSync(fd, uid, gid)
fs.fdatasyncSync(fd)
fs.fstatSync(fd[, options])
fs.fsyncSync(fd)
fs.ftruncateSync(fd[, len])
fs.futimesSync(fd, atime, mtime)
fs.globSync(pattern[, options])
fs.lchmodSync(path, mode)
fs.lchownSync(path, uid, gid)
fs.lutimesSync(path, atime, mtime)
fs.linkSync(existingPath, newPath)
fs.lstatSync(path[, options])
fs.mkdirSync(path[, options])
fs.mkdtempSync(prefix[, options])
fs.mkdtempDisposableSync(prefix[, options])
fs.opendirSync(path[, options])
fs.openSync(path[, flags[, mode]])
fs.readdirSync(path[, options])
fs.readFileSync(path[, options])
fs.readlinkSync(path[, options])
fs.readSync(fd, buffer, offset, length[, position])
fs.readSync(fd, buffer[, options])
fs.readvSync(fd, buffers[, position])
fs.realpathSync(path[, options])
fs.realpathSync.native(path[, options])
fs.renameSync(oldPath, newPath)
fs.rmdirSync(path[, options])
fs.rmSync(path[, options])
fs.statSync(path[, options])
fs.statfsSync(path[, options])
fs.symlinkSync(target, path[, type])
fs.truncateSync(path[, len])
fs.unlinkSync(path)
fs.utimesSync(path, atime, mtime)
fs.writeFileSync(file, data[, options])
fs.writeSync(fd, buffer, offset[, length[, position]])
fs.writeSync(fd, buffer[, options])
fs.writeSync(fd, string[, position[, encoding]])
fs.writevSync(fd, buffers[, position])
- 通用对象
- 类:
fs.Dir
- 类:
fs.Dirent
- 类:
fs.FSWatcher
- 类:
fs.StatWatcher
- 类:
fs.ReadStream
- 类:
fs.Stats
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isDirectory()
stats.isFIFO()
stats.isFile()
stats.isSocket()
stats.isSymbolicLink()
stats.dev
stats.ino
stats.mode
stats.nlink
stats.uid
stats.gid
stats.rdev
stats.size
stats.blksize
stats.blocks
stats.atimeMs
stats.mtimeMs
stats.ctimeMs
stats.birthtimeMs
stats.atimeNs
stats.mtimeNs
stats.ctimeNs
stats.birthtimeNs
stats.atime
stats.mtime
stats.ctime
stats.birthtime
- Stat 时间值
- 类:
fs.StatFs
- 类:
fs.Utf8Stream
- 事件:
'close'
- 事件:
'drain'
- 事件:
'drop'
- 事件:
'error'
- 事件:
'finish'
- 事件:
'ready'
- 事件:
'write'
new fs.Utf8Stream([options])
utf8Stream.append
utf8Stream.contentMode
utf8Stream.destroy()
utf8Stream.end()
utf8Stream.fd
utf8Stream.file
utf8Stream.flush(callback)
utf8Stream.flushSync()
utf8Stream.fsync
utf8Stream.maxLength
utf8Stream.minLength
utf8Stream.mkdir
utf8Stream.mode
utf8Stream.periodicFlush
utf8Stream.reopen(file)
utf8Stream.sync
utf8Stream.write(data)
utf8Stream.writing
utf8Stream[Symbol.dispose]()
- 事件:
- 类:
fs.WriteStream
fs.constants
- 类:
- 注意
- 文件系统
-
索引
- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲区
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入器 API
- 子进程
- 集群
- 命令行选项
- 控制台
- 加密
- 调试器
- 已弃用的 API
- 诊断通道
- DNS
- 域
- 环境变量
- 错误
- 事件
- 文件系统
- 全局对象
- HTTP
- HTTP/2
- HTTPS
- 检查器
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:module
API - 模块:包
- 模块:TypeScript
- 网络
- 操作系统
- 路径
- 性能钩子
- 权限
- 进程
- Punycode
- 查询字符串
- 逐行读取
- REPL
- 报告
- 单一可执行文件应用
- SQLite
- 流
- 字符串解码器
- 测试运行器
- 定时器
- TLS/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用工具
- V8
- 虚拟机
- WASI
- Web Crypto API
- Web Streams API
- 工作线程
- Zlib
- 其他版本
- 选项
文件系统#
源代码: lib/fs.js
node:fs
模块使得能够以一种模仿标准 POSIX 函数的方式与文件系统进行交互。
要使用基于 Promise 的 API
import * as fs from 'node:fs/promises';
const fs = require('node:fs/promises');
要使用回调和同步 API
import * as fs from 'node:fs';
const fs = require('node:fs');
所有文件系统操作都有同步、回调和基于 Promise 的形式,并且可以使用 CommonJS 语法和 ES6 模块(ESM)进行访问。
Promise 示例#
基于 Promise 的操作返回一个 Promise,该 Promise 在异步操作完成时被兑现。
import { unlink } from 'node:fs/promises';
try {
await unlink('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (error) {
console.error('there was an error:', error.message);
}
const { unlink } = require('node:fs/promises');
(async function(path) {
try {
await unlink(path);
console.log(`successfully deleted ${path}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello');
回调示例#
回调形式将一个完成回调函数作为其最后一个参数,并异步调用该操作。传递给完成回调的参数取决于方法,但第一个参数总是保留给异常。如果操作成功完成,则第一个参数为 null
或 undefined
。
import { unlink } from 'node:fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
const { unlink } = require('node:fs');
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
当需要最大性能(在执行时间和内存分配方面)时,node:fs
模块 API 的基于回调的版本比使用 Promise API 更可取。
同步示例#
同步 API 会阻塞 Node.js 事件循环和后续的 JavaScript 执行,直到操作完成。异常会立即抛出,可以使用 try…catch
进行处理,或者让它们冒泡上去。
import { unlinkSync } from 'node:fs';
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
const { unlinkSync } = require('node:fs');
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
Promises API#
fs/promises
API 提供了返回 Promise 的异步文件系统方法。
Promise API 使用底层的 Node.js 线程池在事件循环线程之外执行文件系统操作。这些操作不是同步的或线程安全的。在对同一文件执行多个并发修改时必须小心,否则可能会发生数据损坏。
类: FileHandle
#
一个 <FileHandle> 对象是一个数字文件描述符的对象包装器。
<FileHandle> 对象的实例由 fsPromises.open()
方法创建。
所有的 <FileHandle> 对象都是 <EventEmitter>s。
如果一个 <FileHandle> 没有使用 filehandle.close()
方法关闭,它将尝试自动关闭文件描述符并发出一个进程警告,以帮助防止内存泄漏。请不要依赖此行为,因为它可能不可靠,文件可能不会被关闭。相反,请始终显式关闭 <FileHandle>s。Node.js 将来可能会更改此行为。
事件: 'close'
#
当 <FileHandle> 已被关闭并且不能再使用时,会发出 'close'
事件。
filehandle.appendFile(data[, options])
#
data
<string> | <Buffer> | <TypedArray> | <DataView> | <AsyncIterable> | <Iterable> | <Stream>options
<Object> | <string>encoding
<string> | <null> 默认:'utf8'
signal
<AbortSignal> | <undefined> 允许中止正在进行的 writeFile 操作。默认:undefined
- 返回: <Promise> 成功时兑现为
undefined
。
在操作文件句柄时,模式不能从使用 fsPromises.open()
设置的模式更改。因此,这等同于 filehandle.writeFile()
。
filehandle.close()
#
- 返回: <Promise> 成功时兑现为
undefined
。
在等待句柄上的任何待处理操作完成后,关闭文件句柄。
import { open } from 'node:fs/promises';
let filehandle;
try {
filehandle = await open('thefile.txt', 'r');
} finally {
await filehandle?.close();
}
filehandle.createReadStream([options])
#
options
<Object>encoding
<string> 默认:null
autoClose
<boolean> 默认:true
emitClose
<boolean> 默认:true
start
<integer>end
<integer> 默认:Infinity
highWaterMark
<integer> 默认:64 * 1024
signal
<AbortSignal> | <undefined> 默认:undefined
- 返回: <fs.ReadStream>
options
可以包含 start
和 end
值,以从文件中读取一个字节范围,而不是整个文件。start
和 end
都是包含性的,从 0 开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER
] 范围内。如果省略或为 undefined
,filehandle.createReadStream()
将从当前文件位置顺序读取。encoding
可以是 <Buffer> 接受的任何一种编码。
如果 FileHandle
指向一个只支持阻塞读取的字符设备(如键盘或声卡),读取操作直到有数据可用时才会完成。这可能会阻止进程退出和流自然关闭。
默认情况下,流在被销毁后会发出 'close'
事件。将 emitClose
选项设置为 false
以更改此行为。
import { open } from 'node:fs/promises';
const fd = await open('/dev/input/event0');
// Create a stream from some character device.
const stream = fd.createReadStream();
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
如果 autoClose
为 false,则文件描述符将不会被关闭,即使出现错误也是如此。应用程序有责任关闭它并确保没有文件描述符泄漏。如果 autoClose
设置为 true(默认行为),在 'error'
或 'end'
时,文件描述符将自动关闭。
一个读取 100 字节长的文件的最后 10 个字节的示例
import { open } from 'node:fs/promises';
const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 });
filehandle.createWriteStream([options])
#
options
<Object>- 返回: <fs.WriteStream>
options
也可以包含一个 start
选项,以允许在文件开头之后的某个位置写入数据,允许的值在 [0, Number.MAX_SAFE_INTEGER
] 范围内。修改文件而不是替换它可能需要将 flags
open
选项设置为 r+
而不是默认的 r
。encoding
可以是 <Buffer> 接受的任何一种编码。
如果 autoClose
设置为 true(默认行为),在 'error'
或 'finish'
时,文件描述符将自动关闭。如果 autoClose
为 false,则文件描述符将不会被关闭,即使出现错误也是如此。应用程序有责任关闭它并确保没有文件描述符泄漏。
默认情况下,流在被销毁后会发出 'close'
事件。将 emitClose
选项设置为 false
以更改此行为。
filehandle.datasync()
#
- 返回: <Promise> 成功时兑现为
undefined
。
强制将所有与文件关联的当前排队 I/O 操作同步到操作系统的同步 I/O 完成状态。有关详细信息,请参阅 POSIX fdatasync(2)
文档。
与 filehandle.sync
不同,此方法不刷新修改后的元数据。
filehandle.fd
#
- 类型: <number> 由 <FileHandle> 对象管理的数字文件描述符。
filehandle.read(buffer, offset, length, position)
#
buffer
<Buffer> | <TypedArray> | <DataView> 将被填充读取的文件数据的缓冲区。offset
<integer> 缓冲区中开始填充的位置。默认:0
length
<integer> 要读取的字节数。默认:buffer.byteLength - offset
position
<integer> | <bigint> | <null> 从文件中开始读取数据的位置。如果为null
或-1
,将从当前文件位置读取数据,并且该位置将被更新。如果position
是一个非负整数,则当前文件位置将保持不变。默认:null
- 返回: <Promise> 成功时兑现,返回一个包含两个属性的对象
bytesRead
<integer> 读取的字节数buffer
<Buffer> | <TypedArray> | <DataView> 对传入的buffer
参数的引用。
从文件中读取数据并将其存储在给定的缓冲区中。
如果文件没有被并发修改,当读取的字节数为零时,即到达文件末尾。
filehandle.read([options])
#
options
<Object>buffer
<Buffer> | <TypedArray> | <DataView> 将被填充读取的文件数据的缓冲区。默认:Buffer.alloc(16384)
offset
<integer> 缓冲区中开始填充的位置。默认:0
length
<integer> 要读取的字节数。默认:buffer.byteLength - offset
position
<integer> | <bigint> | <null> 从文件中开始读取数据的位置。如果为null
或-1
,将从当前文件位置读取数据,并且该位置将被更新。如果position
是一个非负整数,则当前文件位置将保持不变。默认:null
- 返回: <Promise> 成功时兑现,返回一个包含两个属性的对象
bytesRead
<integer> 读取的字节数buffer
<Buffer> | <TypedArray> | <DataView> 对传入的buffer
参数的引用。
从文件中读取数据并将其存储在给定的缓冲区中。
如果文件没有被并发修改,当读取的字节数为零时,即到达文件末尾。
filehandle.read(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView> 将被填充读取的文件数据的缓冲区。options
<Object>- 返回: <Promise> 成功时兑现,返回一个包含两个属性的对象
bytesRead
<integer> 读取的字节数buffer
<Buffer> | <TypedArray> | <DataView> 对传入的buffer
参数的引用。
从文件中读取数据并将其存储在给定的缓冲区中。
如果文件没有被并发修改,当读取的字节数为零时,即到达文件末尾。
filehandle.readableWebStream([options])
#
options
<Object>autoClose
<boolean> 当为 true 时,导致 <FileHandle> 在流关闭时被关闭。默认:false
- 返回:<ReadableStream>
返回一个面向字节的 ReadableStream
,可用于读取文件内容。
如果此方法被调用超过一次,或者在 FileHandle
关闭或正在关闭后调用,将会抛出错误。
import {
open,
} from 'node:fs/promises';
const file = await open('./some/file/to/read');
for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
const {
open,
} = require('node:fs/promises');
(async () => {
const file = await open('./some/file/to/read');
for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
})();
虽然 ReadableStream
会将文件读取到完成,但它不会自动关闭 FileHandle
。用户代码仍然必须调用 fileHandle.close()
方法,除非 autoClose
选项设置为 true
。
filehandle.readFile(options)
#
options
<Object> | <string>encoding
<string> | <null> 默认:null
signal
<AbortSignal> 允许中止正在进行的 readFile 操作
- 返回: <Promise> 成功读取后兑现,其值为文件的内容。如果未指定编码(使用
options.encoding
),则数据作为 <Buffer> 对象返回。否则,数据将是字符串。
异步读取文件的全部内容。
如果 options
是一个字符串,则它指定了 encoding
。
<FileHandle> 必须支持读取。
如果在文件句柄上进行了一次或多次 filehandle.read()
调用,然后进行 filehandle.readFile()
调用,数据将从当前位置读取到文件末尾。它并不总是从文件开头读取。
filehandle.readLines([options])
#
options
<Object>- 返回: <readline.InterfaceConstructor>
创建 readline
接口并流式处理文件的便捷方法。有关选项,请参见 filehandle.createReadStream()
。
import { open } from 'node:fs/promises';
const file = await open('./some/file/to/read');
for await (const line of file.readLines()) {
console.log(line);
}
const { open } = require('node:fs/promises');
(async () => {
const file = await open('./some/file/to/read');
for await (const line of file.readLines()) {
console.log(line);
}
})();
filehandle.readv(buffers[, position])
#
buffers
<Buffer[]> | <TypedArray[]> | <DataView[]>position
<integer> | <null> 从文件开头开始读取数据的偏移量。如果position
不是number
,数据将从当前位置读取。默认:null
- 返回: <Promise> 成功时兑现,返回一个包含两个属性的对象
bytesRead
<integer> 读取的字节数buffers
<Buffer[]> | <TypedArray[]> | <DataView[]> 包含对buffers
输入的引用的属性。
从文件中读取并写入到 <ArrayBufferView> 数组
filehandle.stat([options])
#
options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
- 返回: <Promise> 兑现文件的 <fs.Stats>。
filehandle.sync()
#
- 返回: <Promise> 成功时兑现为
undefined
。
请求将打开的文件描述符的所有数据刷新到存储设备。具体实现取决于操作系统和设备。有关更多详细信息,请参阅 POSIX fsync(2)
文档。
filehandle.truncate(len)
#
截断文件。
如果文件大于 len
字节,则文件中仅保留前 len
字节。
以下示例仅保留文件的前四个字节
import { open } from 'node:fs/promises';
let filehandle = null;
try {
filehandle = await open('temp.txt', 'r+');
await filehandle.truncate(4);
} finally {
await filehandle?.close();
}
如果文件先前小于 len
字节,则会对其进行扩展,扩展部分将填充空字节 ('\0'
)
如果 len
为负数,则将使用 0
。
filehandle.utimes(atime, mtime)
#
更改 <FileHandle> 引用的对象的文件系统时间戳,成功后兑现不带任何参数的 Promise。
filehandle.write(buffer, offset[, length[, position]])
#
buffer
<Buffer> | <TypedArray> | <DataView>offset
<integer>buffer
中开始写入数据的位置。length
<integer> 从buffer
写入的字节数。默认:buffer.byteLength - offset
position
<integer> | <null> 从文件开头开始写入buffer
中数据的偏移量。如果position
不是number
,则数据将写入当前位置。有关更多详细信息,请参阅 POSIXpwrite(2)
文档。默认:null
- 返回:<Promise>
将 buffer
写入文件。
该 Promise 将被兑现,并返回一个包含两个属性的对象
bytesWritten
<integer> 写入的字节数buffer
<Buffer> | <TypedArray> | <DataView> 对写入的buffer
的引用。
在未等待 Promise 兑现(或拒绝)的情况下,在同一文件上多次使用 filehandle.write()
是不安全的。对于这种情况,请使用 filehandle.createWriteStream()
。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
filehandle.write(buffer[, options])
#
buffer
<Buffer> | <TypedArray> | <DataView>options
<Object>- 返回:<Promise>
将 buffer
写入文件。
与上面的 filehandle.write
函数类似,此版本接受一个可选的 options
对象。如果未指定 options
对象,它将默认为上述值。
filehandle.write(string[, position[, encoding]])
#
string
<string>position
<integer> | <null> 从文件开头开始写入string
中数据的偏移量。如果position
不是number
,则数据将写入当前位置。有关更多详细信息,请参阅 POSIXpwrite(2)
文档。默认:null
encoding
<string> 预期的字符串编码。默认:'utf8'
- 返回:<Promise>
将 string
写入文件。如果 string
不是字符串,则 Promise 会因错误而拒绝。
该 Promise 将被兑现,并返回一个包含两个属性的对象
在未等待 Promise 兑现(或拒绝)的情况下,在同一文件上多次使用 filehandle.write()
是不安全的。对于这种情况,请使用 filehandle.createWriteStream()
。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
filehandle.writeFile(data, options)
#
data
<string> | <Buffer> | <TypedArray> | <DataView> | <AsyncIterable> | <Iterable> | <Stream>options
<Object> | <string>encoding
<string> | <null> 当data
是字符串时预期的字符编码。默认:'utf8'
signal
<AbortSignal> | <undefined> 允许中止正在进行的 writeFile 操作。默认:undefined
- 返回:<Promise>
异步地将数据写入文件,如果文件已存在则替换该文件。data
可以是字符串、缓冲区、<AsyncIterable> 或 <Iterable> 对象。成功后,Promise 将兑现为不带任何参数的值。
如果 options
是一个字符串,则它指定了 encoding
。
<FileHandle> 必须支持写入。
在未等待 Promise 兑现(或拒绝)的情况下,在同一文件上多次使用 filehandle.writeFile()
是不安全的。
如果在文件句柄上进行了一次或多次 filehandle.write()
调用,然后进行 filehandle.writeFile()
调用,数据将从当前位置写入到文件末尾。它并不总是从文件开头写入。
filehandle.writev(buffers[, position])
#
buffers
<Buffer[]> | <TypedArray[]> | <DataView[]>position
<integer> | <null> 从文件开头开始写入buffers
中数据的偏移量。如果position
不是number
,则数据将写入当前位置。默认:null
- 返回:<Promise>
将 <ArrayBufferView>s 数组写入文件。
该 Promise 将被兑现,并返回一个包含两个属性的对象
bytesWritten
<integer> 写入的字节数buffers
<Buffer[]> | <TypedArray[]> | <DataView[]> 对buffers
输入的引用。
在未等待 Promise 兑现(或拒绝)的情况下,在同一文件上多次调用 writev()
是不安全的。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
filehandle[Symbol.asyncDispose]()
#
调用 filehandle.close()
并返回一个 Promise,该 Promise 在文件句柄关闭时兑现。
fsPromises.access(path[, mode])
#
path
<string> | <Buffer> | <URL>mode
<integer> 默认:fs.constants.F_OK
- 返回: <Promise> 成功时兑现为
undefined
。
测试用户对 path
指定的文件或目录的权限。mode
参数是一个可选的整数,指定要执行的可访问性检查。mode
应该是值 fs.constants.F_OK
或由 fs.constants.R_OK
、fs.constants.W_OK
和 fs.constants.X_OK
中任意一个或多个的按位或组成的掩码(例如 fs.constants.W_OK | fs.constants.R_OK
)。请检查文件访问常量以了解 mode
的可能值。
如果可访问性检查成功,Promise 将兑现为无值。如果任何可访问性检查失败,Promise 将被拒绝并带有一个 <Error> 对象。以下示例检查当前进程是否可以读取和写入文件 /etc/passwd
。
import { access, constants } from 'node:fs/promises';
try {
await access('/etc/passwd', constants.R_OK | constants.W_OK);
console.log('can access');
} catch {
console.error('cannot access');
}
不建议在调用 fsPromises.open()
之前使用 fsPromises.access()
检查文件的可访问性。这样做会引入竞态条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不可访问时引发的错误。
fsPromises.appendFile(path, data[, options])
#
path
<string> | <Buffer> | <URL> | <FileHandle> 文件名或 <FileHandle>data
<string> | <Buffer>options
<Object> | <string>- 返回: <Promise> 成功时兑现为
undefined
。
异步地将数据追加到文件中,如果文件尚不存在则创建文件。data
可以是字符串或 <Buffer>。
如果 options
是一个字符串,则它指定了 encoding
。
mode
选项仅影响新创建的文件。有关更多详细信息,请参见 fs.open()
。
path
可以指定为一个已打开用于追加的 <FileHandle>(使用 fsPromises.open()
)。
fsPromises.chmod(path, mode)
#
更改文件的权限。
fsPromises.chown(path, uid, gid)
#
更改文件的所有权。
fsPromises.copyFile(src, dest[, mode])
#
src
<string> | <Buffer> | <URL> 要复制的源文件名dest
<string> | <Buffer> | <URL> 复制操作的目标文件名mode
<integer> 指定复制操作行为的可选修饰符。可以通过两个或多个值的按位或来创建一个掩码(例如fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
)默认:0
。fs.constants.COPYFILE_EXCL
: 如果dest
已存在,复制操作将失败。fs.constants.COPYFILE_FICLONE
: 复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则会使用备用的复制机制。fs.constants.COPYFILE_FICLONE_FORCE
: 复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则操作将失败。
- 返回: <Promise> 成功时兑现为
undefined
。
异步地将 src
复制到 dest
。默认情况下,如果 dest
已存在,它将被覆盖。
不保证复制操作的原子性。如果在为写入打开目标文件后发生错误,将尝试删除目标文件。
import { copyFile, constants } from 'node:fs/promises';
try {
await copyFile('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
try {
await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
fsPromises.cp(src, dest[, options])
#
src
<string> | <URL> 要复制的源路径。dest
<string> | <URL> 要复制到的目标路径。options
<Object>dereference
<boolean> 解引用符号链接。默认:false
。errorOnExist
<boolean> 当force
为false
且目标存在时,抛出错误。默认:false
。filter
<Function> 用于过滤复制的文件/目录的函数。返回true
以复制该项,返回false
以忽略它。当忽略一个目录时,其所有内容也将被跳过。也可以返回一个解析为true
或false
的Promise
。默认:undefined
。force
<boolean> 覆盖现有的文件或目录。如果将此设置为 false 且目标存在,复制操作将忽略错误。使用errorOnExist
选项来更改此行为。默认:true
。mode
<integer> 复制操作的修饰符。默认:0
。参见fsPromises.copyFile()
的mode
标志。preserveTimestamps
<boolean> 当为true
时,将保留src
的时间戳。默认:false
。recursive
<boolean> 递归复制目录 默认:false
verbatimSymlinks
<boolean> 当为true
时,将跳过符号链接的路径解析。默认:false
- 返回: <Promise> 成功时兑现为
undefined
。
异步地将整个目录结构从 src
复制到 dest
,包括子目录和文件。
将目录复制到另一个目录时,不支持通配符,行为类似于 cp dir1/ dir2/
。
fsPromises.glob(pattern[, options])
#
pattern
<string> | <string[]>options
<Object>cwd
<string> | <URL> 当前工作目录。默认:process.cwd()
exclude
<Function> | <string[]> 用于过滤文件/目录的函数或要排除的 glob 模式列表。如果提供函数,返回true
表示排除该项,返回false
表示包含。默认:undefined
。如果提供字符串数组,则每个字符串都应为指定要排除路径的 glob 模式。注意:不支持否定模式(例如 `!foo.js`)。withFileTypes
<boolean> 如果 glob 应返回 Dirents 形式的路径,则为true
,否则为false
。默认:false
。
- 返回: <AsyncIterator> 一个 AsyncIterator,它产生与模式匹配的文件路径。
import { glob } from 'node:fs/promises';
for await (const entry of glob('**/*.js'))
console.log(entry);
const { glob } = require('node:fs/promises');
(async () => {
for await (const entry of glob('**/*.js'))
console.log(entry);
})();
fsPromises.lchown(path, uid, gid)
#
更改符号链接的所有权。
fsPromises.lutimes(path, atime, mtime)
#
path
<string> | <Buffer> | <URL>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>- 返回: <Promise> 成功时兑现为
undefined
。
以与 fsPromises.utimes()
相同的方式更改文件的访问和修改时间,不同之处在于如果路径引用一个符号链接,则该链接不会被解引用:而是更改符号链接本身的时间戳。
fsPromises.link(existingPath, newPath)
#
existingPath
<string> | <Buffer> | <URL>newPath
<string> | <Buffer> | <URL>- 返回: <Promise> 成功时兑现为
undefined
。
从 existingPath
创建到 newPath
的新链接。有关更多详细信息,请参阅 POSIX link(2)
文档。
fsPromises.lstat(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
- 返回: <Promise> 兑现给定符号链接
path
的 <fs.Stats> 对象。
等同于 fsPromises.stat()
,除非 path
引用一个符号链接,在这种情况下,统计的是链接本身,而不是它引用的文件。有关更多详细信息,请参阅 POSIX lstat(2)
文档。
fsPromises.mkdir(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object> | <integer>- 返回: <Promise> 成功后,如果
recursive
为false
,则兑现为undefined
;如果recursive
为true
,则兑现为创建的第一个目录路径。
异步地创建目录。
可选的 options
参数可以是一个指定 mode
(权限和粘滞位)的整数,或一个带有 mode
属性和 recursive
属性(指示是否应创建父目录)的对象。当 path
是一个已存在的目录时调用 fsPromises.mkdir()
仅在 recursive
为 false 时才会导致拒绝。
import { mkdir } from 'node:fs/promises';
try {
const projectFolder = new URL('./test/project/', import.meta.url);
const createDir = await mkdir(projectFolder, { recursive: true });
console.log(`created ${createDir}`);
} catch (err) {
console.error(err.message);
}
const { mkdir } = require('node:fs/promises');
const { join } = require('node:path');
async function makeDirectory() {
const projectFolder = join(__dirname, 'test', 'project');
const dirCreation = await mkdir(projectFolder, { recursive: true });
console.log(dirCreation);
return dirCreation;
}
makeDirectory().catch(console.error);
fsPromises.mkdtemp(prefix[, options])
#
prefix
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <Promise> 兑现一个包含新创建的临时目录文件系统路径的字符串。
创建一个唯一的临时目录。通过在提供的 prefix
末尾附加六个随机字符来生成唯一的目录名。由于平台不一致,请避免在 prefix
中使用尾随的 X
字符。某些平台,特别是 BSD,可能会返回超过六个随机字符,并用随机字符替换 prefix
中的尾随 X
字符。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定要使用的字符编码。
import { mkdtemp } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
try {
await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
fsPromises.mkdtemp()
方法会将六个随机选择的字符直接附加到 prefix
字符串上。例如,给定一个目录 /tmp
,如果意图是在 /tmp
内 创建一个临时目录,则 prefix
必须以特定于平台的尾随路径分隔符(require('node:path').sep
)结尾。
fsPromises.mkdtempDisposable(prefix[, options])
#
prefix
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <Promise> 兑现一个异步可处置对象的 Promise
path
<string> 创建的目录的路径。remove
<AsyncFunction> 一个删除已创建目录的函数。[Symbol.asyncDispose]
<AsyncFunction> 与remove
相同。
生成的 Promise 持有一个异步可处置对象,其 path
属性保存了创建的目录路径。当该对象被处置时,如果目录仍然存在,它及其内容将被异步删除。如果目录无法删除,处置将抛出错误。该对象有一个异步的 remove()
方法,它将执行相同的任务。
此函数和结果对象上的处置函数都是异步的,因此应与 await
+ await using
一起使用,如 await using dir = await fsPromises.mkdtempDisposable('prefix')
。
有关详细信息,请参阅 fsPromises.mkdtemp()
的文档。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定要使用的字符编码。
fsPromises.open(path, flags[, mode])
#
path
<string> | <Buffer> | <URL>flags
<string> | <number> 参见文件系统flags
的支持。默认:'r'
。mode
<string> | <integer> 如果文件被创建,则设置文件模式(权限和粘滞位)。默认:0o666
(可读可写)- 返回: <Promise> 兑现一个 <FileHandle> 对象。
打开一个 <FileHandle>。
有关更多详细信息,请参阅 POSIX open(2)
文档。
某些字符 (< > : " / \ | ? *
) 在 Windows 下是保留的,如 命名文件、路径和命名空间 所述。在 NTFS 下,如果文件名包含冒号,Node.js 将打开一个文件系统流,如 此 MSDN 页面 所述。
fsPromises.opendir(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>encoding
<string> | <null> 默认:'utf8'
bufferSize
<number> 从目录读取时内部缓冲的目录条目数。较高的值会导致更好的性能,但内存使用量也更高。默认:32
recursive
<boolean> 解析的Dir
将是一个 <AsyncIterable>,包含所有子文件和目录。默认:false
- 返回: <Promise> 兑现一个 <fs.Dir>。
异步打开一个目录进行迭代扫描。有关更多详细信息,请参阅 POSIX opendir(3)
文档。
创建一个 <fs.Dir>,它包含了用于从目录中读取和清理的所有进一步功能。
encoding
选项在打开目录和后续读取操作时设置 path
的编码。
使用异步迭代的示例
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
当使用异步迭代器时,<fs.Dir> 对象将在迭代器退出后自动关闭。
fsPromises.readdir(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>- 返回: <Promise> 兑现一个包含目录中文件名数组的 Promise,不包括
'.'
和'..'
。
读取目录的内容。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定用于文件名的字符编码。如果 encoding
设置为 'buffer'
,返回的文件名将作为 <Buffer> 对象传递。
如果 options.withFileTypes
设置为 true
,返回的数组将包含 <fs.Dirent> 对象。
import { readdir } from 'node:fs/promises';
try {
const files = await readdir(path);
for (const file of files)
console.log(file);
} catch (err) {
console.error(err);
}
fsPromises.readFile(path[, options])
#
path
<string> | <Buffer> | <URL> | <FileHandle> 文件名或FileHandle
options
<Object> | <string>encoding
<string> | <null> 默认:null
flag
<string> 参见文件系统flags
的支持。默认:'r'
。signal
<AbortSignal> 允许中止正在进行的 readFile 操作
- 返回: <Promise> 兑现文件的内容。
异步读取文件的全部内容。
如果未指定编码(使用 options.encoding
),数据将作为 <Buffer> 对象返回。否则,数据将是字符串。
如果 options
是一个字符串,则它指定了编码。
当 path
是一个目录时,fsPromises.readFile()
的行为是平台特定的。在 macOS、Linux 和 Windows 上,Promise 将被拒绝并带有一个错误。在 FreeBSD 上,将返回目录内容的表示。
一个读取与运行代码位于同一目录中的 package.json
文件的示例
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
const { readFile } = require('node:fs/promises');
const { resolve } = require('node:path');
async function logFile() {
try {
const filePath = resolve('./package.json');
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
}
logFile();
可以使用 <AbortSignal> 中止正在进行的 readFile
。如果请求被中止,返回的 Promise 将被拒绝并带有一个 AbortError
import { readFile } from 'node:fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
中止一个正在进行的请求不会中止单个操作系统请求,而是中止 fs.readFile
执行的内部缓冲。
任何指定的 <FileHandle> 都必须支持读取。
fsPromises.readlink(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <Promise> 成功后兑现
linkString
。
读取 path
所引用的符号链接的内容。有关更多详细信息,请参阅 POSIX readlink(2)
文档。成功后,Promise 将兑现 linkString
。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定用于返回的链接路径的字符编码。如果 encoding
设置为 'buffer'
,返回的链接路径将作为 <Buffer> 对象传递。
fsPromises.realpath(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <Promise> 成功后兑现解析的路径。
使用与 fs.realpath.native()
函数相同的语义来确定 path
的实际位置。
仅支持可转换为 UTF8 字符串的路径。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定用于路径的字符编码。如果 encoding
设置为 'buffer'
,返回的路径将作为 <Buffer> 对象传递。
在 Linux 上,当 Node.js 链接到 musl libc 时,procfs 文件系统必须挂载在 /proc
上才能使此函数正常工作。Glibc 没有此限制。
fsPromises.rename(oldPath, newPath)
#
oldPath
<string> | <Buffer> | <URL>newPath
<string> | <Buffer> | <URL>- 返回: <Promise> 成功时兑现为
undefined
。
将 oldPath
重命名为 newPath
。
fsPromises.rmdir(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object> 目前没有公开的选项。以前曾有用于recursive
、maxBusyTries
和emfileWait
的选项,但它们已被弃用和移除。为了向后兼容,仍然接受options
参数,但不会使用它。- 返回: <Promise> 成功时兑现为
undefined
。
移除由 path
标识的目录。
在文件(而不是目录)上使用 fsPromises.rmdir()
会导致在 Windows 上 promise 被拒绝并返回 ENOENT
错误,在 POSIX 上则返回 ENOTDIR
错误。
要获得类似于 Unix 命令 rm -rf
的行为,请使用 fsPromises.rm()
并设置选项 { recursive: true, force: true }
。
fsPromises.rm(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>force
<boolean> 当为true
时,如果path
不存在,异常将被忽略。默认值:false
。maxRetries
<integer> 如果遇到EBUSY
、EMFILE
、ENFILE
、ENOTEMPTY
或EPERM
错误,Node.js 将在每次尝试时以retryDelay
毫秒的线性退避等待时间重试操作。此选项表示重试次数。如果recursive
选项不为true
,则此选项将被忽略。默认值:0
。recursive
<boolean> 如果为true
,则执行递归目录删除。在递归模式下,操作失败时会重试。默认值:false
。retryDelay
<integer> 两次重试之间等待的时间(以毫秒为单位)。如果recursive
选项不为true
,则此选项将被忽略。默认值:100
。
- 返回: <Promise> 成功时兑现为
undefined
。
移除文件和目录(模仿标准的 POSIX rm
实用程序)。
fsPromises.stat(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
- 返回:<Promise> 成功时兑现为给定
path
的 <fs.Stats> 对象。
fsPromises.statfs(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.StatFs> 对象中的数值是否应为bigint
。默认值:false
。
- 返回:<Promise> 成功时兑现为给定
path
的 <fs.StatFs> 对象。
fsPromises.symlink(target, path[, type])
#
target
<string> | <Buffer> | <URL>path
<string> | <Buffer> | <URL>type
<string> | <null> 默认值:null
- 返回: <Promise> 成功时兑现为
undefined
。
创建符号链接。
type
参数仅在 Windows 平台上使用,可以是 'dir'
、'file'
或 'junction'
之一。如果 type
参数为 null
,Node.js 将自动检测 target
类型并使用 'file'
或 'dir'
。如果 target
不存在,将使用 'file'
。Windows 目录连接点要求目标路径是绝对路径。使用 'junction'
时,target
参数将自动规范化为绝对路径。NTFS 卷上的目录连接点只能指向目录。
fsPromises.truncate(path[, len])
#
将 path
处的内容截断(缩短或延长)到 len
字节的长度。
fsPromises.unlink(path)
#
如果 path
指向一个符号链接,则该链接将被移除,而不会影响该链接所指向的文件或目录。如果 path
指向一个非符号链接的文件路径,则该文件将被删除。有关更多详细信息,请参阅 POSIX unlink(2)
文档。
fsPromises.utimes(path, atime, mtime)
#
path
<string> | <Buffer> | <URL>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>- 返回: <Promise> 成功时兑现为
undefined
。
更改 path
所引用对象的文件系统时间戳。
atime
和 mtime
参数遵循以下规则
- 值可以是表示 Unix 纪元时间的数字、
Date
对象或类似'123456789.0'
的数字字符串。 - 如果值无法转换为数字,或者是
NaN
、Infinity
或-Infinity
,则会抛出Error
。
fsPromises.watch(filename[, options])
#
filename
<string> | <Buffer> | <URL>options
<string> | <Object>persistent
<boolean> 指示只要文件被监视,进程是否应继续运行。默认值:true
。recursive
<boolean> 指示是否应监视所有子目录,或仅监视当前目录。这在指定目录时适用,并且仅在受支持的平台上有效(请参阅注意事项)。默认值:false
。encoding
<string> 指定用于传递给监听器的文件名的字符编码。默认值:'utf8'
。signal
<AbortSignal> 一个 <AbortSignal>,用于发出监视器应停止的信号。maxQueue
<number> 指定在返回的 <AsyncIterator> 的迭代之间要排队的事件数量。默认值:2048
。overflow
<string> 当有比maxQueue
允许的更多事件要排队时,可以是'ignore'
或'throw'
。'ignore'
表示溢出事件被丢弃并发出警告,而'throw'
表示抛出异常。默认值:'ignore'
。
- 返回:<AsyncIterator>,其对象具有以下属性
返回一个异步迭代器,用于监视 filename
上的更改,其中 filename
可以是文件或目录。
const { watch } = require('node:fs/promises');
const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 10000);
(async () => {
try {
const watcher = watch(__filename, { signal });
for await (const event of watcher)
console.log(event);
} catch (err) {
if (err.name === 'AbortError')
return;
throw err;
}
})();
在大多数平台上,只要目录中出现或消失文件名,就会发出 'rename'
事件。
fs.watch()
的所有注意事项也适用于 fsPromises.watch()
。
fsPromises.writeFile(file, data[, options])
#
file
<string> | <Buffer> | <URL> | <FileHandle> 文件名或FileHandle
data
<string> | <Buffer> | <TypedArray> | <DataView> | <AsyncIterable> | <Iterable> | <Stream>options
<Object> | <string>encoding
<string> | <null> 默认:'utf8'
mode
<integer> 默认:0o666
flag
<string> 请参阅对文件系统flags
的支持。默认值:'w'
。flush
<boolean> 如果所有数据都成功写入文件,并且flush
为true
,则使用filehandle.sync()
刷新数据。默认值:false
。signal
<AbortSignal> 允许中止正在进行的 writeFile
- 返回: <Promise> 成功时兑现为
undefined
。
异步地将数据写入文件,如果文件已存在则替换该文件。data
可以是字符串、缓冲区、<AsyncIterable> 或 <Iterable> 对象。
如果 data
是缓冲区,则忽略 encoding
选项。
如果 options
是一个字符串,则它指定了编码。
mode
选项仅影响新创建的文件。有关更多详细信息,请参见 fs.open()
。
任何指定的 <FileHandle> 都必须支持写入。
在同一个文件上多次使用 fsPromises.writeFile()
而不等待 promise 解决是不安全的。
与 fsPromises.readFile
类似 - fsPromises.writeFile
是一个便利方法,它在内部执行多次 write
调用以写入传递给它的缓冲区。对于性能敏感的代码,请考虑使用 fs.createWriteStream()
或 filehandle.createWriteStream()
。
可以使用 <AbortSignal> 取消 fsPromises.writeFile()
。取消是“尽力而为”的,可能仍有少量数据被写入。
import { writeFile } from 'node:fs/promises';
import { Buffer } from 'node:buffer';
try {
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
const promise = writeFile('message.txt', data, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
中止正在进行的请求不会中止单个操作系统请求,而是中止 fs.writeFile
执行的内部缓冲。
回调 API#
回调 API 异步执行所有操作,不会阻塞事件循环,然后在完成或出错时调用回调函数。
回调 API 使用底层的 Node.js 线程池在事件循环线程之外执行文件系统操作。这些操作不是同步的或线程安全的。在对同一文件执行多个并发修改时必须小心,否则可能会发生数据损坏。
fs.access(path[, mode], callback)
#
path
<string> | <Buffer> | <URL>mode
<integer> 默认:fs.constants.F_OK
callback
<Function>err
<Error>
测试用户对 path
指定的文件或目录的权限。mode
参数是一个可选的整数,指定要执行的可访问性检查。mode
应该是值 fs.constants.F_OK
或由 fs.constants.R_OK
、fs.constants.W_OK
和 fs.constants.X_OK
中任意一个或多个的按位或组成的掩码(例如 fs.constants.W_OK | fs.constants.R_OK
)。请检查文件访问常量以了解 mode
的可能值。
最后一个参数 callback
是一个回调函数,它会带有一个可能的错误参数被调用。如果任何可访问性检查失败,错误参数将是一个 Error
对象。以下示例检查 package.json
是否存在,以及它是否可读或可写。
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
不要在调用 fs.open()
、fs.readFile()
或 fs.writeFile()
之前使用 fs.access()
检查文件的可访问性。这样做会引入竞态条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不可访问时引发的错误。
写入(不推荐)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
写入(推荐)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
读取(不推荐)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
读取(推荐)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
上面“不推荐”的示例先检查可访问性,然后再使用文件;“推荐”的示例更好,因为它们直接使用文件并处理可能出现的错误。
通常,仅在不会直接使用文件时才检查文件的可访问性,例如,当其可访问性是来自另一个进程的信号时。
在 Windows 上,目录上的访问控制策略 (ACL) 可能会限制对文件或目录的访问。然而,fs.access()
函数不检查 ACL,因此即使 ACL 限制用户读取或写入,它也可能报告路径是可访问的。
fs.appendFile(path, data[, options], callback)
#
path
<string> | <Buffer> | <URL> | <number> 文件名或文件描述符data
<string> | <Buffer>options
<Object> | <string>callback
<Function>err
<Error>
异步地将数据追加到文件中,如果文件尚不存在则创建文件。data
可以是字符串或 <Buffer>。
mode
选项仅影响新创建的文件。有关更多详细信息,请参见 fs.open()
。
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
如果 options
是一个字符串,那么它指定编码
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
path
可以指定为一个已打开用于追加(使用 fs.open()
或 fs.openSync()
)的数字文件描述符。文件描述符不会自动关闭。
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
fs.chmod(path, mode, callback)
#
异步地更改文件的权限。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX chmod(2)
文档。
import { chmod } from 'node:fs';
chmod('my_file.txt', 0o775, (err) => {
if (err) throw err;
console.log('The permissions for file "my_file.txt" have been changed!');
});
文件模式#
在 fs.chmod()
和 fs.chmodSync()
方法中使用的 mode
参数是使用以下常量的逻辑或运算创建的数字位掩码
常量 | 八进制 | 描述 |
---|---|---|
fs.constants.S_IRUSR | 0o400 | 所有者读取 |
fs.constants.S_IWUSR | 0o200 | 所有者写入 |
fs.constants.S_IXUSR | 0o100 | 所有者执行/搜索 |
fs.constants.S_IRGRP | 0o40 | 用户组读取 |
fs.constants.S_IWGRP | 0o20 | 用户组写入 |
fs.constants.S_IXGRP | 0o10 | 用户组执行/搜索 |
fs.constants.S_IROTH | 0o4 | 其他人读取 |
fs.constants.S_IWOTH | 0o2 | 其他人写入 |
fs.constants.S_IXOTH | 0o1 | 其他人执行/搜索 |
构建 mode
的一个更简单的方法是使用一个由三个八进制数字组成的序列(例如 765
)。最左边的数字(示例中的 7
)指定文件所有者的权限。中间的数字(示例中的 6
)指定用户组的权限。最右边的数字(示例中的 5
)指定其他人的权限。
数字 | 描述 |
---|---|
7 | 读、写和执行 |
6 | 读和写 |
5 | 读和执行 |
4 | 只读 |
3 | 写和执行 |
2 | 只写 |
1 | 只执行 |
0 | 无权限 |
例如,八进制值 0o765
表示
- 所有者可以读取、写入和执行该文件。
- 用户组可以读取和写入该文件。
- 其他人可以读取和执行该文件。
在期望文件模式的地方使用原始数字时,任何大于 0o777
的值都可能导致平台特定的行为,这些行为不支持一致地工作。因此,像 S_ISVTX
、S_ISGID
或 S_ISUID
这样的常量没有在 fs.constants
中公开。
注意事项:在 Windows 上,只能更改写权限,并且没有实现用户组、所有者或其他人的权限区分。
fs.chown(path, uid, gid, callback)
#
异步地更改文件的所有者和用户组。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX chown(2)
文档。
fs.close(fd[, callback])
#
fd
<integer>callback
<Function>err
<Error>
关闭文件描述符。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
在任何其他 fs
操作正在使用的文件描述符 (fd
) 上调用 fs.close()
可能会导致未定义的行为。
有关更多详细信息,请参阅 POSIX close(2)
文档。
fs.copyFile(src, dest[, mode], callback)
#
src
<string> | <Buffer> | <URL> 要复制的源文件名dest
<string> | <Buffer> | <URL> 复制操作的目标文件名mode
<integer> 复制操作的修饰符。默认值:0
。callback
<Function>err
<Error>
异步地将 src
复制到 dest
。默认情况下,如果 dest
已存在,则会被覆盖。除了一个可能的异常外,没有其他参数会传递给回调函数。Node.js 不保证复制操作的原子性。如果在目标文件已打开以供写入后发生错误,Node.js 将尝试移除目标文件。
mode
是一个可选的整数,用于指定复制操作的行为。可以通过两个或多个值的按位或运算来创建一个掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
)。
fs.constants.COPYFILE_EXCL
: 如果dest
已存在,复制操作将失败。fs.constants.COPYFILE_FICLONE
: 复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则会使用备用的复制机制。fs.constants.COPYFILE_FICLONE_FORCE
: 复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则操作将失败。
import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
fs.cp(src, dest[, options], callback)
#
src
<string> | <URL> 要复制的源路径。dest
<string> | <URL> 要复制到的目标路径。options
<Object>dereference
<boolean> 解引用符号链接。默认:false
。errorOnExist
<boolean> 当force
为false
且目标存在时,抛出错误。默认:false
。filter
<Function> 用于过滤复制的文件/目录的函数。返回true
以复制该项,返回false
以忽略它。当忽略一个目录时,其所有内容也将被跳过。也可以返回一个解析为true
或false
的Promise
。默认:undefined
。force
<boolean> 覆盖现有的文件或目录。如果将此设置为 false 且目标存在,复制操作将忽略错误。使用errorOnExist
选项来更改此行为。默认:true
。mode
<integer> 复制操作的修饰符。默认值:0
。请参阅fs.copyFile()
的mode
标志。preserveTimestamps
<boolean> 当为true
时,将保留src
的时间戳。默认:false
。recursive
<boolean> 递归复制目录 默认:false
verbatimSymlinks
<boolean> 当为true
时,将跳过符号链接的路径解析。默认:false
callback
<Function>err
<Error>
异步地将整个目录结构从 src
复制到 dest
,包括子目录和文件。
将目录复制到另一个目录时,不支持通配符,行为类似于 cp dir1/ dir2/
。
fs.createReadStream(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>flags
<string> 请参阅对文件系统flags
的支持。默认值:'r'
。encoding
<string> 默认:null
fd
<integer> | <FileHandle> 默认值:null
mode
<integer> 默认:0o666
autoClose
<boolean> 默认:true
emitClose
<boolean> 默认:true
start
<integer>end
<integer> 默认:Infinity
highWaterMark
<integer> 默认:64 * 1024
fs
<Object> | <null> 默认值:null
signal
<AbortSignal> | <null> 默认值:null
- 返回: <fs.ReadStream>
options
可以包含 start
和 end
值,以读取文件中的一个字节范围,而不是整个文件。start
和 end
都是包含的,从 0 开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER
] 范围内。如果指定了 fd
并且省略了 start
或为 undefined
,fs.createReadStream()
会从当前文件位置顺序读取。encoding
可以是 <Buffer> 接受的任何一种。
如果指定了 fd
,ReadStream
将忽略 path
参数,并使用指定的文件描述符。这意味着不会发出 'open'
事件。fd
应该是阻塞的;非阻塞的 fd
应该传递给 <net.Socket>。
如果 fd
指向一个只支持阻塞读取的字符设备(如键盘或声卡),读取操作在有数据可用之前不会完成。这可能会阻止进程退出和流自然关闭。
默认情况下,流在被销毁后会发出 'close'
事件。将 emitClose
选项设置为 false
以更改此行为。
通过提供 fs
选项,可以覆盖 open
、read
和 close
对应的 fs
实现。当提供 fs
选项时,必须覆盖 read
。如果没有提供 fd
,也必须覆盖 open
。如果 autoClose
为 true
,也必须覆盖 close
。
import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
如果 autoClose
为 false,则文件描述符将不会被关闭,即使出现错误也是如此。应用程序有责任关闭它并确保没有文件描述符泄漏。如果 autoClose
设置为 true(默认行为),在 'error'
或 'end'
时,文件描述符将自动关闭。
mode
设置文件模式(权限和粘滞位),但仅在文件被创建时有效。
一个读取 100 字节长的文件的最后 10 个字节的示例
import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });
如果 options
是一个字符串,则它指定了编码。
fs.createWriteStream(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>flags
<string> 请参阅对文件系统flags
的支持。默认值:'w'
。encoding
<string> 默认值:'utf8'
fd
<integer> | <FileHandle> 默认值:null
mode
<integer> 默认:0o666
autoClose
<boolean> 默认:true
emitClose
<boolean> 默认:true
start
<integer>fs
<Object> | <null> 默认值:null
signal
<AbortSignal> | <null> 默认值:null
highWaterMark
<number> 默认:16384
flush
<boolean> 如果为true
,则在关闭底层文件描述符之前将其刷新。默认:false
。
- 返回: <fs.WriteStream>
options
也可以包含一个 start
选项,允许在文件开头之后某个位置写入数据,允许的值在 [0, Number.MAX_SAFE_INTEGER
] 范围内。修改文件而不是替换它可能需要将 flags
选项设置为 r+
而不是默认的 w
。encoding
可以是 <Buffer> 接受的任何一种。
如果 autoClose
设置为 true(默认行为),在 'error'
或 'finish'
时,文件描述符将自动关闭。如果 autoClose
为 false,则文件描述符将不会被关闭,即使出现错误也是如此。应用程序有责任关闭它并确保没有文件描述符泄漏。
默认情况下,流在被销毁后会发出 'close'
事件。将 emitClose
选项设置为 false
以更改此行为。
通过提供 fs
选项,可以覆盖 open
、write
、writev
和 close
对应的 fs
实现。覆盖 write()
而不覆盖 writev()
会降低性能,因为一些优化 (_writev()
) 将被禁用。当提供 fs
选项时,至少需要覆盖 write
和 writev
中的一个。如果没有提供 fd
选项,也需要覆盖 open
。如果 autoClose
为 true
,也需要覆盖 close
。
与 <fs.ReadStream> 类似,如果指定了 fd
,<fs.WriteStream> 将忽略 path
参数,并使用指定的文件描述符。这意味着不会发出 'open'
事件。fd
应该是阻塞的;非阻塞的 fd
应该传递给 <net.Socket>。
如果 options
是一个字符串,则它指定了编码。
fs.exists(path, callback)
#
path
<string> | <Buffer> | <URL>callback
<Function>exists
<boolean>
通过检查文件系统来测试给定 path
处的元素是否存在。然后用 true 或 false 调用 callback
参数。
import { exists } from 'node:fs';
exists('/etc/passwd', (e) => {
console.log(e ? 'it exists' : 'no passwd!');
});
此回调的参数与其他 Node.js 回调不一致。通常,Node.js 回调的第一个参数是 err
参数,后面可以选择性地跟其他参数。而 fs.exists()
的回调只有一个布尔参数。这是推荐使用 fs.access()
而不是 fs.exists()
的原因之一。
如果 path
是一个符号链接,它会被跟随。因此,如果 path
存在但指向一个不存在的元素,回调函数将接收到值 false
。
不建议在调用 fs.open()
、fs.readFile()
或 fs.writeFile()
之前使用 fs.exists()
来检查文件是否存在。这样做会引入竞态条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不存在时引发的错误。
写入(不推荐)
import { exists, open, close } from 'node:fs';
exists('myfile', (e) => {
if (e) {
console.error('myfile already exists');
} else {
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
}
});
写入(推荐)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
读取(不推荐)
import { open, close, exists } from 'node:fs';
exists('myfile', (e) => {
if (e) {
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
} else {
console.error('myfile does not exist');
}
});
读取(推荐)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
上面“不推荐”的示例先检查存在性,然后再使用文件;“推荐”的示例更好,因为它们直接使用文件并处理可能出现的错误。
通常,只有在不会直接使用文件时才检查文件的存在性,例如当其存在性是来自另一个进程的信号时。
fs.fchmod(fd, mode, callback)
#
fd
<integer>mode
<string> | <integer>callback
<Function>err
<Error>
设置文件的权限。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX fchmod(2)
文档。
fs.fchown(fd, uid, gid, callback)
#
fd
<integer>uid
<integer>gid
<integer>callback
<Function>err
<Error>
设置文件的所有者。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX fchown(2)
文档。
fs.fdatasync(fd, callback)
#
fd
<integer>callback
<Function>err
<Error>
强制所有与文件关联的当前排队的 I/O 操作进入操作系统的同步 I/O 完成状态。详情请参阅 POSIX fdatasync(2)
文档。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
fs.fstat(fd[, options], callback)
#
fd
<integer>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
callback
<Function>err
<Error>stats
<fs.Stats>
使用文件描述符的 <fs.Stats> 调用回调函数。
有关更多详细信息,请参阅 POSIX fstat(2)
文档。
fs.fsync(fd, callback)
#
fd
<integer>callback
<Function>err
<Error>
请求将打开的文件描述符的所有数据刷新到存储设备。具体实现是操作系统和设备特定的。详情请参阅 POSIX fsync(2)
文档。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
fs.ftruncate(fd[, len], callback)
#
fd
<integer>len
<integer> 默认:0
callback
<Function>err
<Error>
截断文件描述符。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX ftruncate(2)
文档。
如果文件描述符引用的文件大于 len
字节,文件中将只保留前 len
个字节。
例如,以下程序只保留文件的前四个字节
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
});
如果文件先前小于 len
字节,则会对其进行扩展,扩展部分将填充空字节 ('\0'
)
如果 len
为负数,则将使用 0
。
fs.futimes(fd, atime, mtime, callback)
#
fd
<integer>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>callback
<Function>err
<Error>
更改所提供的文件描述符引用的对象的文件系统时间戳。请参阅 fs.utimes()
。
fs.glob(pattern[, options], callback)
#
-
pattern
<string> | <string[]> -
options
<Object>cwd
<string> | <URL> 当前工作目录。默认:process.cwd()
exclude
<Function> | <string[]> 用于过滤文件/目录的函数,或要排除的 glob 模式列表。如果提供函数,返回true
以排除项目,返回false
以包含项目。默认值:undefined
。withFileTypes
<boolean> 如果 glob 应返回 Dirents 形式的路径,则为true
,否则为false
。默认:false
。
-
callback
<Function>err
<Error>
-
检索与指定模式匹配的文件。
import { glob } from 'node:fs';
glob('**/*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
const { glob } = require('node:fs');
glob('**/*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
fs.lchmod(path, mode, callback)
#
path
<string> | <Buffer> | <URL>mode
<integer>callback
<Function>err
<Error> | <AggregateError>
更改符号链接的权限。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
此方法仅在 macOS 上实现。
有关更多详细信息,请参阅 POSIX lchmod(2)
文档。
fs.lchown(path, uid, gid, callback)
#
设置符号链接的所有者。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX lchown(2)
文档。
fs.lutimes(path, atime, mtime, callback)
#
path
<string> | <Buffer> | <URL>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>callback
<Function>err
<Error>
以与 fs.utimes()
相同的方式更改文件的访问和修改时间,不同之处在于,如果路径指向一个符号链接,则链接本身不会被解引用:而是更改符号链接本身的时间戳。
除了一个可能的异常外,没有其他参数会传递给完成回调函数。
fs.link(existingPath, newPath, callback)
#
existingPath
<string> | <Buffer> | <URL>newPath
<string> | <Buffer> | <URL>callback
<Function>err
<Error>
创建从 existingPath
到 newPath
的新链接。有关更多详细信息,请参阅 POSIX link(2)
文档。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
fs.lstat(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
callback
<Function>err
<Error>stats
<fs.Stats>
检索路径所引用的符号链接的 <fs.Stats>。回调函数接收两个参数 (err, stats)
,其中 stats
是一个 <fs.Stats> 对象。lstat()
与 stat()
相同,不同之处在于如果 path
是一个符号链接,那么会获取链接本身的状态,而不是它所引用的文件。
有关更多详细信息,请参阅 POSIX lstat(2)
文档。
fs.mkdir(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object> | <integer>callback
<Function>err
<Error>path
<string> | <undefined> 仅在recursive
设置为true
并创建目录时存在。
异步地创建目录。
回调函数接收一个可能的异常,并且如果 recursive
是 true
,则接收第一个创建的目录路径 (err[, path])
。当 recursive
是 true
时,如果未创建目录(例如,如果它之前已创建),path
仍然可以是 undefined
。
可选的 options
参数可以是一个指定 mode
(权限和粘滞位)的整数,或者是一个带有 mode
属性和 recursive
属性(指示是否应创建父目录)的对象。当 path
是一个已存在的目录时,只有在 recursive
为 false 时调用 fs.mkdir()
才会导致错误。如果 recursive
为 false 且目录存在,则会发生 EEXIST
错误。
import { mkdir } from 'node:fs';
// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
在 Windows 上,即使使用递归,在根目录上使用 fs.mkdir()
也会导致错误
import { mkdir } from 'node:fs';
mkdir('/', { recursive: true }, (err) => {
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
有关更多详细信息,请参阅 POSIX mkdir(2)
文档。
fs.mkdtemp(prefix[, options], callback)
#
prefix
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
callback
<Function>
创建一个唯一的临时目录。
生成六个随机字符附加在必需的 prefix
后面,以创建一个唯一的临时目录。由于平台不一致,请避免在 prefix
中使用尾随的 X
字符。某些平台,特别是 BSD,可以返回超过六个随机字符,并用随机字符替换 prefix
中的尾随 X
字符。
创建的目录路径作为字符串传递给回调函数的第二个参数。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定要使用的字符编码。
import { mkdtemp } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
fs.mkdtemp()
方法会将六个随机选择的字符直接附加到 prefix
字符串。例如,给定一个目录 /tmp
,如果意图是在 /tmp
内部创建一个临时目录,则 prefix
必须以平台特定的路径分隔符结尾(require('node:path').sep
)。
import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';
// The parent directory for the new temporary directory
const tmpDir = tmpdir();
// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmpabc123`.
// A new temporary directory is created at the file system root
// rather than *within* the /tmp directory.
});
// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmp/abc123`.
// A new temporary directory is created within
// the /tmp directory.
});
fs.open(path[, flags[, mode]], callback)
#
path
<string> | <Buffer> | <URL>flags
<string> | <number> 参见文件系统flags
的支持。默认:'r'
。mode
<string> | <integer> 默认值:0o666
(可读可写)callback
<Function>
异步文件打开。有关更多详细信息,请参阅 POSIX open(2)
文档。
mode
设置文件模式(权限和粘滞位),但仅在文件被创建时有效。在 Windows 上,只能操作写权限;请参阅 fs.chmod()
。
回调函数接收两个参数 (err, fd)
。
某些字符 (< > : " / \ | ? *
) 在 Windows 下是保留的,如 命名文件、路径和命名空间 所述。在 NTFS 下,如果文件名包含冒号,Node.js 将打开一个文件系统流,如 此 MSDN 页面 所述。
基于 fs.open()
的函数也表现出此行为:fs.writeFile()
、fs.readFile()
等。
fs.openAsBlob(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>type
<string> blob 的可选 mime 类型。
- 返回:<Promise> 成功时兑现为一个 <Blob>。
返回一个 <Blob>,其数据由给定文件支持。
在创建 <Blob> 后不得修改文件。任何修改都将导致读取 <Blob> 数据时失败并返回 DOMException
错误。在创建 Blob
时以及每次读取之前,都会对文件进行同步的 stat 操作,以检测文件数据在磁盘上是否已被修改。
import { openAsBlob } from 'node:fs';
const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();
const { openAsBlob } = require('node:fs');
(async () => {
const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();
})();
fs.opendir(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object>callback
<Function>
异步打开一个目录。有关更多详细信息,请参阅 POSIX opendir(3)
文档。
创建一个 <fs.Dir>,它包含了用于从目录中读取和清理的所有进一步功能。
encoding
选项在打开目录和后续读取操作时设置 path
的编码。
fs.read(fd, buffer, offset, length, position, callback)
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView> 将要写入数据的缓冲区。offset
<integer> 在buffer
中写入数据的位置。length
<integer> 要读取的字节数。position
<integer> | <bigint> | <null> 指定从文件中的何处开始读取。如果position
是null
或-1
,则将从当前文件位置读取数据,并且文件位置将被更新。如果position
是一个非负整数,则文件位置将保持不变。callback
<Function>
从 fd
指定的文件中读取数据。
回调函数接收三个参数:(err, bytesRead, buffer)
。
如果文件没有被并发修改,当读取的字节数为零时,即到达文件末尾。
如果此方法作为其 util.promisify()
版本被调用,它将返回一个 promise,该 promise 解析为一个带有 bytesRead
和 buffer
属性的 Object
。
fs.read()
方法从文件描述符 (fd
) 指定的文件中读取数据。length
参数指示 Node.js 将尝试从内核读取的最大字节数。然而,由于各种原因,实际读取的字节数 (bytesRead
) 可能低于指定的 length
。
例如:
- 如果文件短于指定的
length
,bytesRead
将被设置为实际读取的字节数。 - 如果在缓冲区被填满之前文件遇到 EOF(文件结束),Node.js 将读取所有可用字节直到遇到 EOF,并且回调中的
bytesRead
参数将指示实际读取的字节数,这可能小于指定的length
。 - 如果文件位于慢速网络文件系统上或在读取期间遇到任何其他问题,
bytesRead
可能低于指定的length
。
因此,在使用 fs.read()
时,检查 bytesRead
值以确定实际从文件中读取了多少字节非常重要。根据您的应用程序逻辑,您可能需要处理 bytesRead
低于指定 length
的情况,例如,如果您需要最小数量的字节,则可以将读取调用包装在循环中。
此行为类似于 POSIX preadv2
函数。
fs.read(fd[, options], callback)
#
fd
<integer>options
<Object>buffer
<Buffer> | <TypedArray> | <DataView> 默认值:Buffer.alloc(16384)
offset
<integer> 默认:0
length
<integer> 默认:buffer.byteLength - offset
position
<integer> | <bigint> | <null> 默认值:null
callback
<Function>
与 fs.read()
函数类似,此版本接受一个可选的 options
对象。如果未指定 options
对象,则将使用上述默认值。
fs.read(fd, buffer[, options], callback)
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView> 将要写入数据的缓冲区。options
<Object>callback
<Function>
与 fs.read()
函数类似,此版本接受一个可选的 options
对象。如果未指定 options
对象,则将使用上述默认值。
fs.readdir(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>callback
<Function>err
<Error>files
<string[]> | <Buffer[]> | <fs.Dirent[]>
读取目录的内容。回调函数接收两个参数 (err, files)
,其中 files
是目录中文件名的数组,不包括 '.'
和 '..'
。
有关更多详细信息,请参阅 POSIX readdir(3)
文档。
可选的 options
参数可以是一个指定编码的字符串,或者是一个带有 encoding
属性的对象,用于指定传递给回调函数的文件名所使用的字符编码。如果 encoding
设置为 'buffer'
,返回的文件名将作为 <Buffer> 对象传递。
如果 options.withFileTypes
设置为 true
,files
数组将包含 <fs.Dirent> 对象。
fs.readFile(path[, options], callback)
#
path
<string> | <Buffer> | <URL> | <integer> 文件名或文件描述符options
<Object> | <string>encoding
<string> | <null> 默认:null
flag
<string> 参见文件系统flags
的支持。默认:'r'
。signal
<AbortSignal> 允许中止正在进行的 readFile 操作
callback
<Function>err
<Error> | <AggregateError>data
<string> | <Buffer>
异步读取文件的全部内容。
import { readFile } from 'node:fs';
readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
回调函数接收两个参数 (err, data)
,其中 data
是文件的内容。
如果未指定编码,则返回原始缓冲区。
如果 options
是一个字符串,那么它指定编码
import { readFile } from 'node:fs';
readFile('/etc/passwd', 'utf8', callback);
当路径是目录时,fs.readFile()
和 fs.readFileSync()
的行为是平台特定的。在 macOS、Linux 和 Windows 上,将返回一个错误。在 FreeBSD 上,将返回目录内容的表示。
import { readFile } from 'node:fs';
// macOS, Linux, and Windows
readFile('<directory>', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
});
// FreeBSD
readFile('<directory>', (err, data) => {
// => null, <data>
});
可以使用 AbortSignal
中止正在进行的请求。如果请求被中止,回调函数将以 AbortError
被调用。
import { readFile } from 'node:fs';
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
// ...
});
// When you want to abort the request
controller.abort();
fs.readFile()
函数会缓冲整个文件。为了最小化内存成本,在可能的情况下,首选通过 fs.createReadStream()
进行流式处理。
中止一个正在进行的请求不会中止单个操作系统请求,而是中止 fs.readFile
执行的内部缓冲。
文件描述符#
- 任何指定的文件描述符都必须支持读取。
- 如果将文件描述符指定为
path
,它不会自动关闭。 - 读取将从当前位置开始。例如,如果文件已有
'Hello World'
,并且用文件描述符读取了六个字节,那么使用相同文件描述符调用fs.readFile()
将得到'World'
,而不是'Hello World'
。
性能考量#
fs.readFile()
方法异步地将文件内容一次一个块地读入内存,允许事件循环在每个块之间转换。这使得读取操作对可能正在使用底层 libuv 线程池的其他活动的影响较小,但意味着将完整文件读入内存需要更长的时间。
额外的读取开销在不同系统上可能差异很大,并取决于所读取文件的类型。如果文件类型不是常规文件(例如管道),并且 Node.js 无法确定实际文件大小,则每个读取操作将加载 64 KiB 的数据。对于常规文件,每个读取操作将处理 512 KiB 的数据。
对于需要尽快读取文件内容的应用程序,最好直接使用 fs.read()
,并由应用程序代码自行管理读取文件的全部内容。
Node.js GitHub 问题 #25741 提供了更多信息以及对不同 Node.js 版本中 fs.readFile()
对多种文件大小性能的详细分析。
fs.readlink(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
callback
<Function>
读取 path
所引用的符号链接的内容。回调函数接收两个参数 (err, linkString)
。
有关更多详细信息,请参阅 POSIX readlink(2)
文档。
可选的 options
参数可以是一个指定编码的字符串,或者是一个带有 encoding
属性的对象,用于指定传递给回调函数的链接路径所使用的字符编码。如果 encoding
设置为 'buffer'
,返回的链接路径将作为 <Buffer> 对象传递。
fs.readv(fd, buffers[, position], callback)
#
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> | <null> 默认:null
callback
<Function>err
<Error>bytesRead
<integer>buffers
<ArrayBufferView[]>
使用 readv()
从 fd
指定的文件中读取数据,并写入一个 ArrayBufferView
数组。
position
是从文件开头开始读取数据的偏移量。如果 typeof position !== 'number'
,则将从当前位置读取数据。
回调函数将接收三个参数:err
、bytesRead
和 buffers
。bytesRead
是从文件中读取的字节数。
如果此方法作为其 util.promisify()
版本被调用,它将返回一个 promise,该 promise 解析为一个带有 bytesRead
和 buffers
属性的 Object
。
fs.realpath(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
callback
<Function>
通过解析 .
、..
和符号链接来异步计算规范路径名。
规范路径名不一定是唯一的。硬链接和绑定挂载可以通过许多路径名暴露文件系统实体。
此函数的行为类似于 realpath(3)
,但有一些例外
-
在不区分大小写的文件系统上不执行大小写转换。
-
符号链接的最大数量是平台无关的,通常比原生
realpath(3)
实现支持的数量要高(得多)。
回调函数接收两个参数 (err, resolvedPath)
。可能会使用 process.cwd
来解析相对路径。
仅支持可转换为 UTF8 字符串的路径。
可选的 options
参数可以是一个指定编码的字符串,或者是一个带有 encoding
属性的对象,用于指定传递给回调函数的路径所使用的字符编码。如果 encoding
设置为 'buffer'
,返回的路径将作为 <Buffer> 对象传递。
如果 path
解析为一个套接字或管道,该函数将返回该对象的系统相关名称。
不存在的路径会导致 ENOENT 错误。error.path
是绝对文件路径。
fs.realpath.native(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
callback
<Function>
异步 realpath(3)
。
回调函数接收两个参数 (err, resolvedPath)
。
仅支持可转换为 UTF8 字符串的路径。
可选的 options
参数可以是一个指定编码的字符串,或者是一个带有 encoding
属性的对象,用于指定传递给回调函数的路径所使用的字符编码。如果 encoding
设置为 'buffer'
,返回的路径将作为 <Buffer> 对象传递。
在 Linux 上,当 Node.js 链接到 musl libc 时,procfs 文件系统必须挂载在 /proc
上才能使此函数正常工作。Glibc 没有此限制。
fs.rename(oldPath, newPath, callback)
#
oldPath
<string> | <Buffer> | <URL>newPath
<string> | <Buffer> | <URL>callback
<Function>err
<Error>
异步地将 oldPath
处的文件重命名为 newPath
提供的路径名。如果 newPath
已存在,它将被覆盖。如果 newPath
处存在一个目录,则会引发错误。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
另请参阅:rename(2)
。
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
fs.rmdir(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object> 目前没有公开的选项。以前曾有用于recursive
、maxBusyTries
和emfileWait
的选项,但它们已被弃用和移除。为了向后兼容,仍然接受options
参数,但不会使用它。callback
<Function>err
<Error>
异步 rmdir(2)
。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
在文件(而不是目录)上使用 fs.rmdir()
会在 Windows 上导致 ENOENT
错误,在 POSIX 上导致 ENOTDIR
错误。
要获得类似于 Unix 命令 rm -rf
的行为,请使用 fs.rm()
并设置选项 { recursive: true, force: true }
。
fs.rm(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object>force
<boolean> 当为true
时,如果path
不存在,异常将被忽略。默认值:false
。maxRetries
<integer> 如果遇到EBUSY
、EMFILE
、ENFILE
、ENOTEMPTY
或EPERM
错误,Node.js 将在每次尝试时以retryDelay
毫秒的线性退避等待时间重试操作。此选项表示重试次数。如果recursive
选项不为true
,则此选项将被忽略。默认值:0
。recursive
<boolean> 如果为true
,则执行递归删除。在递归模式下,操作失败时会重试。默认值:false
。retryDelay
<integer> 两次重试之间等待的时间(以毫秒为单位)。如果recursive
选项不为true
,则此选项将被忽略。默认值:100
。
callback
<Function>err
<Error>
异步地移除文件和目录(模仿标准的 POSIX rm
实用程序)。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
fs.stat(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
callback
<Function>err
<Error>stats
<fs.Stats>
异步 stat(2)
。回调函数接收两个参数 (err, stats)
,其中 stats
是一个 <fs.Stats> 对象。
如果发生错误,err.code
将是常见系统错误之一。
fs.stat()
会跟随符号链接。要查看链接本身,请使用 fs.lstat()
。
不建议在调用 fs.open()
、fs.readFile()
或 fs.writeFile()
之前使用 fs.stat()
来检查文件是否存在。相反,用户代码应该直接打开/读取/写入文件,并处理文件不可用时引发的错误。
要检查文件是否存在而不对其进行后续操作,建议使用 fs.access()
。
例如,给定以下目录结构
- txtDir
-- file.txt
- app.js
下一个程序将检查给定路径的状态
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i < pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
结果输出将类似于
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
fs.statfs(path[, options], callback)
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.StatFs> 对象中的数值是否应为bigint
。默认值:false
。
callback
<Function>err
<Error>stats
<fs.StatFs>
异步 statfs(2)
。返回有关包含 path
的已挂载文件系统的信息。回调函数接收两个参数 (err, stats)
,其中 stats
是一个 <fs.StatFs> 对象。
如果发生错误,err.code
将是常见系统错误之一。
fs.symlink(target, path[, type], callback)
#
target
<string> | <Buffer> | <URL>path
<string> | <Buffer> | <URL>type
<string> | <null> 默认值:null
callback
<Function>err
<Error>
创建名为 path
的链接,指向 target
。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
有关更多详细信息,请参阅 POSIX symlink(2)
文档。
type
参数仅在 Windows 上可用,在其他平台上会被忽略。它可以设置为 'dir'
、'file'
或 'junction'
。如果 type
参数为 null
,Node.js 将自动检测 target
类型并使用 'file'
或 'dir'
。如果 target
不存在,将使用 'file'
。Windows 目录连接点要求目标路径是绝对路径。使用 'junction'
时,target
参数将自动规范化为绝对路径。NTFS 卷上的目录连接点只能指向目录。
相对目标是相对于链接的父目录。
import { symlink } from 'node:fs';
symlink('./mew', './mewtwo', callback);
上面的例子创建了一个名为 mewtwo
的符号链接,它指向同一目录下的 mew
$ tree .
.
├── mew
└── mewtwo -> ./mew
fs.truncate(path[, len], callback)
#
path
<string> | <Buffer> | <URL>len
<integer> 默认:0
callback
<Function>err
<Error> | <AggregateError>
截断文件。除了一个可能的异常外,没有其他参数会传递给完成回调函数。文件描述符也可以作为第一个参数传递。在这种情况下,会调用 fs.ftruncate()
。
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
const { truncate } = require('node:fs');
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
传递文件描述符已弃用,并可能在将来导致抛出错误。
有关更多详细信息,请参阅 POSIX truncate(2)
文档。
fs.unlink(path, callback)
#
path
<string> | <Buffer> | <URL>callback
<Function>err
<Error>
异步地移除文件或符号链接。除了一个可能的异常外,没有其他参数会传递给完成回调函数。
import { unlink } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
unlink('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was deleted');
});
fs.unlink()
对目录不起作用,无论其是否为空。要移除目录,请使用 fs.rmdir()
。
有关更多详细信息,请参阅 POSIX unlink(2)
文档。
fs.unwatchFile(filename[, listener])
#
filename
<string> | <Buffer> | <URL>listener
<Function> 可选,先前使用fs.watchFile()
附加的监听器
停止监视 filename
的更改。如果指定了 listener
,则只移除该特定的监听器。否则,将移除*所有*监听器,从而有效地停止对 filename
的监视。
使用未被监视的文件名调用 fs.unwatchFile()
是一个无操作,而不是错误。
使用 fs.watch()
比 fs.watchFile()
和 fs.unwatchFile()
更高效。在可能的情况下,应使用 fs.watch()
代替 fs.watchFile()
和 fs.unwatchFile()
。
fs.utimes(path, atime, mtime, callback)
#
path
<string> | <Buffer> | <URL>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>callback
<Function>err
<Error>
更改 path
所引用对象的文件系统时间戳。
atime
和 mtime
参数遵循以下规则
- 值可以是表示以秒为单位的 Unix 纪元时间的数字、
Date
对象或类似'123456789.0'
的数字字符串。 - 如果值无法转换为数字,或者是
NaN
、Infinity
或-Infinity
,则会抛出Error
。
fs.watch(filename[, options][, listener])
#
filename
<string> | <Buffer> | <URL>options
<string> | <Object>persistent
<boolean> 指示只要文件被监视,进程是否应继续运行。默认值:true
。recursive
<boolean> 指示是否应监视所有子目录,或仅监视当前目录。这在指定目录时适用,并且仅在受支持的平台上有效(请参阅注意事项)。默认值:false
。encoding
<string> 指定用于传递给监听器的文件名的字符编码。默认值:'utf8'
。signal
<AbortSignal> 允许使用 AbortSignal 关闭监视器。
listener
<Function> | <undefined> 默认值:undefined
- 返回:<fs.FSWatcher>
监视 filename
的变化,其中 filename
可以是文件或目录。
第二个参数是可选的。如果 options
以字符串形式提供,则它指定了 encoding
。否则 options
应该作为一个对象传递。
监听器回调函数接收两个参数 (eventType, filename)
。eventType
的值是 'rename'
或 'change'
,而 filename
是触发事件的文件的名称。
在大多数平台上,只要目录中出现或消失文件名,就会发出 'rename'
事件。
监听器回调附加到由 <fs.FSWatcher> 触发的 'change'
事件上,但这与 eventType
的 'change'
值不是一回事。
如果传递了 signal
,中止相应的 AbortController 将会关闭返回的 <fs.FSWatcher>。
注意事项#
fs.watch
API 在不同平台上的表现不完全一致,并且在某些情况下不可用。
在 Windows 系统上,如果被监视的目录被移动或重命名,将不会触发任何事件。当被监视的目录被删除时,会报告一个 EPERM
错误。
fs.watch
API 不提供任何针对文件系统上恶意行为的保护。例如,在 Windows 上,它是通过监视目录中的更改而不是特定文件来实现的。这允许替换一个文件,而 fs 会报告在新文件上发生了具有相同文件名的更改。
可用性#
此功能依赖于底层操作系统提供文件系统变更通知的方式。
- 在 Linux 系统上,它使用
inotify(7)
。 - 在 BSD 系统上,它使用
kqueue(2)
。 - 在 macOS 上,它对文件使用
kqueue(2)
,对目录使用FSEvents
。 - 在 SunOS 系统(包括 Solaris 和 SmartOS)上,它使用
event ports
。 - 在 Windows 系统上,此功能依赖于
ReadDirectoryChangesW
。 - 在 AIX 系统上,此功能依赖于
AHAFS
,该功能必须被启用。 - 在 IBM i 系统上,不支持此功能。
如果由于某种原因底层功能不可用,那么 fs.watch()
将无法工作,并可能抛出异常。例如,在使用虚拟化软件(如 Vagrant 或 Docker)时,监视网络文件系统(NFS、SMB 等)或主机文件系统上的文件或目录可能不可靠,在某些情况下甚至不可能。
仍然可以使用 fs.watchFile()
,它使用 stat 轮询,但这种方法更慢且可靠性较低。
Inodes#
在 Linux 和 macOS 系统上,fs.watch()
将路径解析为一个 inode 并监视该 inode。如果被监视的路径被删除并重新创建,它会被分配一个新的 inode。监视器会为删除操作触发一个事件,但会继续监视*原始*的 inode。新 inode 的事件将不会被触发。这是预期的行为。
AIX 文件在文件的整个生命周期内保留相同的 inode。在 AIX 上保存并关闭一个被监视的文件将导致两次通知(一次用于添加新内容,一次用于截断)。
filename 参数#
在回调中提供 filename
参数仅在 Linux、macOS、Windows 和 AIX 上受支持。即使在支持的平台上,也不能保证总是提供 filename
。因此,不要假设回调中总是提供了 filename
参数,并为其为 null
的情况准备一些后备逻辑。
import { watch } from 'node:fs';
watch('somedir', (eventType, filename) => {
console.log(`event type is: ${eventType}`);
if (filename) {
console.log(`filename provided: ${filename}`);
} else {
console.log('filename not provided');
}
});
fs.watchFile(filename[, options], listener)
#
filename
<string> | <Buffer> | <URL>options
<Object>listener
<Function>current
<fs.Stats>previous
<fs.Stats>
- 返回: <fs.StatWatcher>
监视 filename
的变化。每次访问文件时,都会调用回调函数 listener
。
options
参数可以省略。如果提供,它应该是一个对象。options
对象可以包含一个名为 persistent
的布尔值,表示只要文件被监视,进程是否应继续运行。options
对象可以指定一个 interval
属性,表示轮询目标的频率(以毫秒为单位)。
listener
接收两个参数:当前的 stat 对象和之前的 stat 对象。
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
这些 stat 对象是 fs.Stat
的实例。如果 bigint
选项为 true
,这些对象中的数值将被指定为 BigInt
。
要收到文件被修改而不仅仅是被访问的通知,需要比较 curr.mtimeMs
和 prev.mtimeMs
。
当 fs.watchFile
操作导致 ENOENT
错误时,它将调用一次监听器,所有字段都为零(或者对于日期,是 Unix 纪元时间)。如果之后文件被创建,监听器将被再次调用,并附带最新的 stat 对象。这是自 v0.10 以来的功能变化。
使用 fs.watch()
比 fs.watchFile
和 fs.unwatchFile
更高效。如果可能,应使用 fs.watch
代替 fs.watchFile
和 fs.unwatchFile
。
当一个被 fs.watchFile()
监视的文件消失后又重新出现时,第二次回调事件(文件重新出现)中的 previous
的内容将与第一次回调事件(文件消失)中的 previous
的内容相同。
这发生在以下情况:
- 文件被删除,然后被恢复
- 文件被重命名,然后再次重命名回其原始名称
fs.write(fd, buffer, offset[, length[, position]], callback)
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView>offset
<integer> 默认:0
length
<integer> 默认:buffer.byteLength - offset
position
<integer> | <null> 默认:null
callback
<Function>err
<Error>bytesWritten
<integer>buffer
<Buffer> | <TypedArray> | <DataView>
将 buffer
写入由 fd
指定的文件。
offset
决定了要写入的缓冲区部分,length
是一个整数,指定了要写入的字节数。
position
指的是从文件开头开始的偏移量,数据应被写入该位置。如果 typeof position !== 'number'
,数据将被写入当前位置。请参阅 pwrite(2)
。
回调函数将接收三个参数 (err, bytesWritten, buffer)
,其中 bytesWritten
指定了从 buffer
中写入了多少个*字节*。
如果此方法作为其 util.promisify()
ed 版本被调用,它会返回一个 Promise,该 Promise 解析为一个具有 bytesWritten
和 buffer
属性的 Object
。
在没有等待回调的情况下,在同一个文件上多次使用 fs.write()
是不安全的。对于这种情况,推荐使用 fs.createWriteStream()
。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
fs.write(fd, buffer[, options], callback)
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView>options
<Object>callback
<Function>err
<Error>bytesWritten
<integer>buffer
<Buffer> | <TypedArray> | <DataView>
将 buffer
写入由 fd
指定的文件。
与上面的 fs.write
函数类似,此版本接受一个可选的 options
对象。如果未指定 options
对象,它将使用上述默认值。
fs.write(fd, string[, position[, encoding]], callback)
#
fd
<integer>string
<string>position
<integer> | <null> 默认:null
encoding
<string> 默认值:'utf8'
callback
<Function>
将 string
写入由 fd
指定的文件。如果 string
不是字符串,则抛出异常。
position
指的是从文件开头开始的偏移量,数据应被写入该位置。如果 typeof position !== 'number'
,数据将被写入当前位置。请参阅 pwrite(2)
。
encoding
是期望的字符串编码。
回调函数将接收参数 (err, written, string)
,其中 written
指定了写入所传入字符串需要多少个*字节*。写入的字节数不一定等于写入的字符串字符数。请参阅 Buffer.byteLength
。
在没有等待回调的情况下,在同一个文件上多次使用 fs.write()
是不安全的。对于这种情况,推荐使用 fs.createWriteStream()
。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
在 Windows 上,如果文件描述符连接到控制台(例如 fd == 1
或 stdout
),无论使用何种编码,包含非 ASCII 字符的字符串默认都不会被正确渲染。可以通过使用 chcp 65001
命令更改活动代码页来配置控制台以正确渲染 UTF-8。有关更多详细信息,请参阅 chcp 文档。
fs.writeFile(file, data[, options], callback)
#
file
<string> | <Buffer> | <URL> | <integer> 文件名或文件描述符data
<string> | <Buffer> | <TypedArray> | <DataView>options
<Object> | <string>encoding
<string> | <null> 默认:'utf8'
mode
<integer> 默认:0o666
flag
<string> 请参阅对文件系统flags
的支持。默认值:'w'
。flush
<boolean> 如果所有数据都成功写入文件,并且flush
为true
,则使用fs.fsync()
来刷新数据。默认值:false
。signal
<AbortSignal> 允许中止正在进行的 writeFile
callback
<Function>err
<Error> | <AggregateError>
当 file
是文件名时,异步地将数据写入文件,如果文件已存在则替换它。data
可以是字符串或缓冲区。
当 file
是文件描述符时,其行为类似于直接调用 fs.write()
(推荐这样做)。请参阅下面关于使用文件描述符的说明。
如果 data
是缓冲区,则忽略 encoding
选项。
mode
选项仅影响新创建的文件。有关更多详细信息,请参见 fs.open()
。
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
如果 options
是一个字符串,那么它指定编码
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
在没有等待回调的情况下,在同一个文件上多次使用 fs.writeFile()
是不安全的。对于这种情况,推荐使用 fs.createWriteStream()
。
与 fs.readFile
类似 - fs.writeFile
是一个便利方法,它在内部执行多次 write
调用来写入传递给它的缓冲区。对于性能敏感的代码,请考虑使用 fs.createWriteStream()
。
可以使用 <AbortSignal> 来取消 fs.writeFile()
。取消是“尽力而为”的,很可能仍有部分数据被写入。
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
// When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
中止正在进行的请求不会中止单个操作系统请求,而是中止 fs.writeFile
执行的内部缓冲。
使用文件描述符的 fs.writeFile()
#
当 file
是文件描述符时,行为几乎与直接调用 fs.write()
完全相同,例如:
import { write } from 'node:fs';
import { Buffer } from 'node:buffer';
write(fd, Buffer.from(data, options.encoding), callback);
与直接调用 fs.write()
的区别在于,在某些不寻常的条件下,fs.write()
可能只写入缓冲区的一部分,并需要重试以写入剩余的数据,而 fs.writeFile()
会一直重试,直到数据完全写入(或发生错误)。
这一点的影响是常见的混淆来源。在文件描述符的情况下,文件不会被替换!数据不一定写入文件的开头,文件原始数据可能会保留在新写入数据的前面和/或后面。
例如,如果连续两次调用 fs.writeFile()
,第一次写入字符串 'Hello'
,然后写入字符串 ', World'
,文件将包含 'Hello, World'
,并且可能包含一些文件的原始数据(取决于原始文件的大小和文件描述符的位置)。如果使用文件名而不是描述符,文件将保证只包含 ', World'
。
fs.writev(fd, buffers[, position], callback)
#
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> | <null> 默认:null
callback
<Function>err
<Error>bytesWritten
<integer>buffers
<ArrayBufferView[]>
使用 writev()
将一个 ArrayBufferView
数组写入由 fd
指定的文件。
position
是从文件开头开始的偏移量,数据应被写入该位置。如果 typeof position !== 'number'
,数据将写入当前位置。
回调函数将接收三个参数:err
、bytesWritten
和 buffers
。bytesWritten
是从 buffers
中写入的字节数。
如果此方法被 util.promisify()
处理,它将返回一个 Promise,该 Promise 解析为一个具有 bytesWritten
和 buffers
属性的 Object
。
在没有等待回调的情况下,在同一个文件上多次使用 fs.writev()
是不安全的。对于这种情况,请使用 fs.createWriteStream()
。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
同步 API#
同步 API 同步执行所有操作,会阻塞事件循环,直到操作完成或失败。
fs.accessSync(path[, mode])
#
同步测试用户对 path
指定的文件或目录的权限。mode
参数是一个可选的整数,用于指定要执行的可访问性检查。mode
应该是值 fs.constants.F_OK
或由 fs.constants.R_OK
、fs.constants.W_OK
和 fs.constants.X_OK
中任意值的位或(bitwise OR)组成的掩码(例如 fs.constants.W_OK | fs.constants.R_OK
)。有关 mode
的可能值,请查看 文件访问常量。
如果任何可访问性检查失败,将抛出一个 Error
。否则,该方法将返回 undefined
。
import { accessSync, constants } from 'node:fs';
try {
accessSync('etc/passwd', constants.R_OK | constants.W_OK);
console.log('can read/write');
} catch (err) {
console.error('no access!');
}
fs.appendFileSync(path, data[, options])
#
path
<string> | <Buffer> | <URL> | <number> 文件名或文件描述符data
<string> | <Buffer>options
<Object> | <string>
同步地将数据追加到文件中,如果文件尚不存在则创建它。data
可以是字符串或 <Buffer>。
mode
选项仅影响新创建的文件。有关更多详细信息,请参见 fs.open()
。
import { appendFileSync } from 'node:fs';
try {
appendFileSync('message.txt', 'data to append');
console.log('The "data to append" was appended to file!');
} catch (err) {
/* Handle the error */
}
如果 options
是一个字符串,那么它指定编码
import { appendFileSync } from 'node:fs';
appendFileSync('message.txt', 'data to append', 'utf8');
path
可以指定为一个已打开用于追加(使用 fs.open()
或 fs.openSync()
)的数字文件描述符。文件描述符不会自动关闭。
import { openSync, closeSync, appendFileSync } from 'node:fs';
let fd;
try {
fd = openSync('message.txt', 'a');
appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
/* Handle the error */
} finally {
if (fd !== undefined)
closeSync(fd);
}
fs.chownSync(path, uid, gid)
#
同步更改文件的所有者和组。返回 undefined
。这是 fs.chown()
的同步版本。
有关更多详细信息,请参阅 POSIX chown(2)
文档。
fs.closeSync(fd)
#
fd
<integer>
关闭文件描述符。返回 undefined
。
在任何当前正通过任何其他 fs
操作使用的文件描述符(fd
)上调用 fs.closeSync()
可能会导致未定义的行为。
有关更多详细信息,请参阅 POSIX close(2)
文档。
fs.copyFileSync(src, dest[, mode])
#
src
<string> | <Buffer> | <URL> 要复制的源文件名dest
<string> | <Buffer> | <URL> 复制操作的目标文件名mode
<integer> 复制操作的修饰符。默认值:0
。
同步地将 src
复制到 dest
。默认情况下,如果 dest
已存在,则会被覆盖。返回 undefined
。Node.js 不保证复制操作的原子性。如果在为写入打开目标文件后发生错误,Node.js 将尝试删除目标文件。
mode
是一个可选的整数,用于指定复制操作的行为。可以通过两个或多个值的按位或运算来创建一个掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
)。
fs.constants.COPYFILE_EXCL
: 如果dest
已存在,复制操作将失败。fs.constants.COPYFILE_FICLONE
: 复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则会使用备用的复制机制。fs.constants.COPYFILE_FICLONE_FORCE
: 复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则操作将失败。
import { copyFileSync, constants } from 'node:fs';
// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
fs.cpSync(src, dest[, options])
#
src
<string> | <URL> 要复制的源路径。dest
<string> | <URL> 要复制到的目标路径。options
<Object>dereference
<boolean> 解引用符号链接。默认:false
。errorOnExist
<boolean> 当force
为false
且目标存在时,抛出错误。默认:false
。filter
<Function> 用于过滤被复制文件/目录的函数。返回true
以复制该项,返回false
以忽略它。当忽略一个目录时,其所有内容也将被跳过。默认值:undefined
force
<boolean> 覆盖现有的文件或目录。如果将此设置为 false 且目标存在,复制操作将忽略错误。使用errorOnExist
选项来更改此行为。默认:true
。mode
<integer> 复制操作的修饰符。默认值:0
。参见fs.copyFileSync()
的mode
标志。preserveTimestamps
<boolean> 当为true
时,将保留src
的时间戳。默认:false
。recursive
<boolean> 递归复制目录 默认:false
verbatimSymlinks
<boolean> 当为true
时,将跳过符号链接的路径解析。默认:false
同步地将整个目录结构从 src
复制到 dest
,包括子目录和文件。
将目录复制到另一个目录时,不支持通配符,行为类似于 cp dir1/ dir2/
。
fs.existsSync(path)
#
如果路径存在则返回 true
,否则返回 false
。
有关详细信息,请参阅此 API 的异步版本文档:fs.exists()
。
fs.exists()
已被弃用,但 fs.existsSync()
没有。fs.exists()
的 callback
参数接受的参数与其他 Node.js 回调不一致。fs.existsSync()
不使用回调。
import { existsSync } from 'node:fs';
if (existsSync('/etc/passwd'))
console.log('The path exists.');
fs.fdatasyncSync(fd)
#
fd
<integer>
强制将与文件关联的所有当前排队的 I/O 操作同步到操作系统的同步 I/O 完成状态。有关详细信息,请参阅 POSIX fdatasync(2)
文档。返回 undefined
。
fs.fstatSync(fd[, options])
#
fd
<integer>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。
- 返回: <fs.Stats>
检索文件描述符的 <fs.Stats>。
有关更多详细信息,请参阅 POSIX fstat(2)
文档。
fs.fsyncSync(fd)
#
fd
<integer>
请求将打开的文件描述符的所有数据刷新到存储设备。具体实现因操作系统和设备而异。有关更多详细信息,请参阅 POSIX fsync(2)
文档。返回 undefined
。
fs.futimesSync(fd, atime, mtime)
#
fs.futimes()
的同步版本。返回 undefined
。
fs.globSync(pattern[, options])
#
pattern
<string> | <string[]>options
<Object>cwd
<string> | <URL> 当前工作目录。默认:process.cwd()
exclude
<Function> | <string[]> 用于过滤文件/目录的函数,或要排除的 glob 模式列表。如果提供函数,返回true
以排除项目,返回false
以包含项目。默认值:undefined
。withFileTypes
<boolean> 如果 glob 应返回 Dirents 形式的路径,则为true
,否则为false
。默认:false
。
- 返回: <string[]> 匹配模式的文件路径。
import { globSync } from 'node:fs';
console.log(globSync('**/*.js'));
const { globSync } = require('node:fs');
console.log(globSync('**/*.js'));
fs.lchmodSync(path, mode)
#
更改符号链接的权限。返回 undefined
。
此方法仅在 macOS 上实现。
有关更多详细信息,请参阅 POSIX lchmod(2)
文档。
fs.lutimesSync(path, atime, mtime)
#
path
<string> | <Buffer> | <URL>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>
更改由 path
引用的符号链接的文件系统时间戳。返回 undefined
,或者当参数不正确或操作失败时抛出异常。这是 fs.lutimes()
的同步版本。
fs.linkSync(existingPath, newPath)
#
从 existingPath
到 newPath
创建一个新的链接。有关更多详细信息,请参阅 POSIX link(2)
文档。返回 undefined
。
fs.lstatSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。throwIfNoEntry
<boolean> 如果没有文件系统条目存在,是否抛出异常,而不是返回undefined
。默认值:true
。
- 返回: <fs.Stats>
检索由 path
引用的符号链接的 <fs.Stats>。
有关更多详细信息,请参阅 POSIX lstat(2)
文档。
fs.mkdirSync(path[, options])
#
同步创建一个目录。返回 undefined
,或者如果 recursive
是 true
,则返回创建的第一个目录路径。这是 fs.mkdir()
的同步版本。
有关更多详细信息,请参阅 POSIX mkdir(2)
文档。
fs.mkdtempSync(prefix[, options])
#
prefix
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <string>
返回创建的目录路径。
有关详细信息,请参阅此 API 的异步版本文档:fs.mkdtemp()
。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定要使用的字符编码。
fs.mkdtempDisposableSync(prefix[, options])
#
prefix
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <Object> 一个可释放的对象
path
<string> 创建的目录的路径。remove
<Function> 一个移除已创建目录的函数。[Symbol.dispose]
<Function> 与remove
相同。
返回一个可释放的对象,其 path
属性保存着创建的目录路径。当该对象被释放时,如果目录仍然存在,它及其内容将被移除。如果目录无法删除,释放操作将抛出错误。该对象有一个 remove()
方法,可以执行相同的任务。
有关详细信息,请参阅 fs.mkdtemp()
的文档。
此 API 没有基于回调的版本,因为它设计用于 using
语法。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定要使用的字符编码。
fs.opendirSync(path[, options])
#
同步打开一个目录。请参阅 opendir(3)
。
创建一个 <fs.Dir>,它包含了用于从目录中读取和清理的所有进一步功能。
encoding
选项在打开目录和后续读取操作时设置 path
的编码。
fs.openSync(path[, flags[, mode]])
#
path
<string> | <Buffer> | <URL>flags
<string> | <number> 默认值:'r'
. 请参阅 文件系统flags
的支持。mode
<string> | <integer> 默认值:0o666
- 返回:<number>
返回一个表示文件描述符的整数。
有关详细信息,请参阅此 API 的异步版本文档:fs.open()
。
fs.readdirSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>- 返回: <string[]> | <Buffer[]> | <fs.Dirent[]>
读取目录的内容。
有关更多详细信息,请参阅 POSIX readdir(3)
文档。
可选的 options
参数可以是一个指定编码的字符串,或一个具有 encoding
属性的对象,该属性指定返回的文件名使用的字符编码。如果 encoding
设置为 'buffer'
,返回的文件名将作为 <Buffer> 对象传递。
如果 options.withFileTypes
设置为 true
,结果将包含 <fs.Dirent> 对象。
fs.readFileSync(path[, options])
#
path
<string> | <Buffer> | <URL> | <integer> 文件名或文件描述符options
<Object> | <string>encoding
<string> | <null> 默认:null
flag
<string> 参见文件系统flags
的支持。默认:'r'
。
- 返回: <string> | <Buffer>
返回 path
的内容。
有关详细信息,请参阅此 API 的异步版本文档:fs.readFile()
。
如果指定了 encoding
选项,则此函数返回一个字符串。否则它返回一个缓冲区。
与 fs.readFile()
类似,当路径是目录时,fs.readFileSync()
的行为是平台特定的。
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
fs.readlinkSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <string> | <Buffer>
返回符号链接的字符串值。
有关更多详细信息,请参阅 POSIX readlink(2)
文档。
可选的 options
参数可以是一个指定编码的字符串,或一个带有 encoding
属性的对象,指定用于返回的链接路径的字符编码。如果 encoding
设置为 'buffer'
,返回的链接路径将作为 <Buffer> 对象传递。
fs.readSync(fd, buffer, offset, length[, position])
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView>offset
<integer>length
<integer>position
<integer> | <bigint> | <null> 默认值:null
- 返回:<number>
返回 bytesRead
的数量。
有关详细信息,请参阅此 API 的异步版本文档:fs.read()
。
fs.readSync(fd, buffer[, options])
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView>options
<Object>- 返回:<number>
返回 bytesRead
的数量。
与上面的 fs.readSync
函数类似,此版本接受一个可选的 options
对象。如果未指定 options
对象,它将使用上述默认值。
有关详细信息,请参阅此 API 的异步版本文档:fs.read()
。
fs.readvSync(fd, buffers[, position])
#
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> | <null> 默认:null
- 返回: <number> 读取的字节数。
有关详细信息,请参阅此 API 的异步版本文档:fs.readv()
。
fs.realpathSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <string> | <Buffer>
返回解析后的路径名。
有关详细信息,请参阅此 API 的异步版本文档:fs.realpath()
。
fs.realpathSync.native(path[, options])
#
path
<string> | <Buffer> | <URL>options
<string> | <Object>encoding
<string> 默认值:'utf8'
- 返回: <string> | <Buffer>
同步的 realpath(3)
。
仅支持可转换为 UTF8 字符串的路径。
可选的 options
参数可以是一个指定编码的字符串,或一个具有 encoding
属性的对象,该属性指定返回路径使用的字符编码。如果 encoding
设置为 'buffer'
,返回的路径将作为 <Buffer> 对象传递。
在 Linux 上,当 Node.js 链接到 musl libc 时,procfs 文件系统必须挂载在 /proc
上才能使此函数正常工作。Glibc 没有此限制。
fs.renameSync(oldPath, newPath)
#
将文件从 oldPath
重命名为 newPath
。返回 undefined
。
有关更多详细信息,请参阅 POSIX rename(2)
文档。
fs.rmdirSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object> 目前没有公开的选项。以前曾有用于recursive
、maxBusyTries
和emfileWait
的选项,但它们已被弃用和移除。为了向后兼容,仍然接受options
参数,但不会使用它。
同步的 rmdir(2)
。返回 undefined
。
对文件(非目录)使用 fs.rmdirSync()
会在 Windows 上导致 ENOENT
错误,在 POSIX 上导致 ENOTDIR
错误。
要获得类似于 Unix 命令 rm -rf
的行为,请使用带有选项 { recursive: true, force: true }
的 fs.rmSync()
。
fs.rmSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>force
<boolean> 当为true
时,如果path
不存在,异常将被忽略。默认值:false
。maxRetries
<integer> 如果遇到EBUSY
、EMFILE
、ENFILE
、ENOTEMPTY
或EPERM
错误,Node.js 将在每次尝试时以retryDelay
毫秒的线性退避等待时间重试操作。此选项表示重试次数。如果recursive
选项不为true
,则此选项将被忽略。默认值:0
。recursive
<boolean> 如果为true
,则执行递归目录删除。在递归模式下,操作失败时会重试。默认值:false
。retryDelay
<integer> 两次重试之间等待的时间(以毫秒为单位)。如果recursive
选项不为true
,则此选项将被忽略。默认值:100
。
同步删除文件和目录(模仿标准 POSIX rm
工具)。返回 undefined
。
fs.statSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.Stats> 对象中的数值是否应为bigint
。默认:false
。throwIfNoEntry
<boolean> 如果没有文件系统条目存在,是否抛出异常,而不是返回undefined
。默认值:true
。
- 返回: <fs.Stats>
检索路径的 <fs.Stats>。
fs.statfsSync(path[, options])
#
path
<string> | <Buffer> | <URL>options
<Object>bigint
<boolean> 返回的 <fs.StatFs> 对象中的数值是否应为bigint
。默认值:false
。
- 返回: <fs.StatFs>
同步的 statfs(2)
。返回有关包含 path
的已挂载文件系统的信息。
如果发生错误,err.code
将是常见系统错误之一。
fs.symlinkSync(target, path[, type])
#
target
<string> | <Buffer> | <URL>path
<string> | <Buffer> | <URL>type
<string> | <null> 默认值:null
- 返回:
undefined
。
有关详细信息,请参阅此 API 的异步版本文档:fs.symlink()
。
fs.truncateSync(path[, len])
#
截断文件。返回 undefined
。也可以将文件描述符作为第一个参数传递。在这种情况下,将调用 fs.ftruncateSync()
。
传递文件描述符已弃用,并可能在将来导致抛出错误。
fs.utimesSync(path, atime, mtime)
#
path
<string> | <Buffer> | <URL>atime
<number> | <string> | <Date>mtime
<number> | <string> | <Date>- 返回:
undefined
。
有关详细信息,请参阅此 API 的异步版本文档:fs.utimes()
。
fs.writeFileSync(file, data[, options])
#
file
<string> | <Buffer> | <URL> | <integer> 文件名或文件描述符data
<string> | <Buffer> | <TypedArray> | <DataView>options
<Object> | <string>- 返回:
undefined
。
mode
选项仅影响新创建的文件。有关更多详细信息,请参见 fs.open()
。
有关详细信息,请参阅此 API 的异步版本文档:fs.writeFile()
。
fs.writeSync(fd, buffer, offset[, length[, position]])
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView>offset
<integer> 默认:0
length
<integer> 默认:buffer.byteLength - offset
position
<integer> | <null> 默认:null
- 返回: <number> 写入的字节数。
有关详细信息,请参阅此 API 的异步版本文档:fs.write(fd, buffer...)
。
fs.writeSync(fd, buffer[, options])
#
fd
<integer>buffer
<Buffer> | <TypedArray> | <DataView>options
<Object>- 返回: <number> 写入的字节数。
有关详细信息,请参阅此 API 的异步版本文档:fs.write(fd, buffer...)
。
fs.writeSync(fd, string[, position[, encoding]])
#
fd
<integer>string
<string>position
<integer> | <null> 默认:null
encoding
<string> 默认值:'utf8'
- 返回: <number> 写入的字节数。
有关详细信息,请参阅此 API 的异步版本文档:fs.write(fd, string...)
。
fs.writevSync(fd, buffers[, position])
#
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> | <null> 默认:null
- 返回: <number> 写入的字节数。
有关详细信息,请参阅此 API 的异步版本文档:fs.writev()
。
通用对象#
通用对象由所有文件系统 API 变体(promise、回调和同步)共享。
类: fs.Dir
#
表示目录流的类。
由 fs.opendir()
、fs.opendirSync()
或 fsPromises.opendir()
创建。
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
当使用异步迭代器时,<fs.Dir> 对象将在迭代器退出后自动关闭。
dir.close(callback)
#
callback
<Function>err
<Error>
异步关闭目录的底层资源句柄。随后的读取将导致错误。
在资源句柄关闭后,将调用 callback
。
dir.closeSync()
#
同步关闭目录的底层资源句柄。随后的读取将导致错误。
dir.read()
#
- 返回: <Promise> 使用 <fs.Dirent> | <null> Fulfill
通过 readdir(3)
异步读取下一个目录条目,并作为 <fs.Dirent> 返回。
返回一个 promise,该 promise 将使用一个 <fs.Dirent> 来 fulfill,或者如果没有更多目录条目可读,则为 null
。
此函数返回的目录条目没有特定顺序,由操作系统的底层目录机制提供。在遍历目录时添加或删除的条目可能不包含在迭代结果中。
dir.read(callback)
#
callback
<Function>err
<Error>dirent
<fs.Dirent> | <null>
通过 readdir(3)
异步读取下一个目录条目,并作为 <fs.Dirent> 返回。
读取完成后,将使用一个 <fs.Dirent> 来调用 callback
,或者如果没有更多目录条目可读,则为 null
。
此函数返回的目录条目没有特定顺序,由操作系统的底层目录机制提供。在遍历目录时添加或删除的条目可能不包含在迭代结果中。
dir.readSync()
#
- 返回: <fs.Dirent> | <null>
同步读取下一个目录条目,并作为 <fs.Dirent> 返回。有关更多详细信息,请参阅 POSIX readdir(3)
文档。
如果没有更多目录条目可读,将返回 null
。
此函数返回的目录条目没有特定顺序,由操作系统的底层目录机制提供。在遍历目录时添加或删除的条目可能不包含在迭代结果中。
dir[Symbol.asyncIterator]()
#
- 返回: <AsyncIterator> 一个 <fs.Dirent> 的 AsyncIterator
异步迭代目录,直到所有条目都被读取。有关更多详细信息,请参阅 POSIX readdir(3)
文档。
异步迭代器返回的条目始终是 <fs.Dirent>。来自 dir.read()
的 null
情况在内部处理。
有关示例,请参阅 <fs.Dir>。
此迭代器返回的目录条目没有特定顺序,由操作系统的底层目录机制提供。在遍历目录时添加或删除的条目可能不包含在迭代结果中。
dir[Symbol.asyncDispose]()
#
如果目录句柄是打开的,则调用 dir.close()
,并返回一个在释放完成时 fulfill 的 promise。
dir[Symbol.dispose]()
#
如果目录句柄是打开的,则调用 dir.closeSync()
,并返回 undefined
。
类: fs.Dirent
#
表示目录条目,可以是目录中的文件或子目录,由从 <fs.Dir> 读取时返回。目录条目是文件名和文件类型对的组合。
此外,当使用 withFileTypes
选项为 true
调用 fs.readdir()
或 fs.readdirSync()
时,结果数组将填充 <fs.Dirent> 对象,而不是字符串或 <Buffer>。
dirent.name
#
这个 <fs.Dirent> 对象所引用的文件名。此值的类型由传递给 fs.readdir()
或 fs.readdirSync()
的 options.encoding
决定。
类: fs.FSWatcher
#
- 继承自 <EventEmitter>
成功调用 fs.watch()
方法将返回一个新的 <fs.FSWatcher> 对象。
所有 <fs.FSWatcher> 对象在特定被监视文件被修改时都会发出一个 'change'
事件。
事件: 'change'
#
当被监视的目录或文件发生变化时发出。更多详情请参阅 fs.watch()
。
filename
参数可能不会提供,这取决于操作系统的支持。如果提供了 filename
,并且 fs.watch()
调用时其 encoding
选项设置为 'buffer'
,则它将以 <Buffer> 形式提供,否则 filename
将是一个 UTF-8 字符串。
import { watch } from 'node:fs';
// Example when handled through fs.watch() listener
watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
if (filename) {
console.log(filename);
// Prints: <Buffer ...>
}
});
事件: 'close'
#
当监视器停止监视变化时发出。已关闭的 <fs.FSWatcher> 对象在事件处理器中不再可用。
watcher.close()
#
停止监视给定的 <fs.FSWatcher> 上的变化。一旦停止,<fs.FSWatcher> 对象将不再可用。
watcher.ref()
#
当调用时,请求 Node.js 事件循环只要 <fs.FSWatcher> 处于活动状态就*不要*退出。多次调用 watcher.ref()
将没有效果。
默认情况下,所有 <fs.FSWatcher> 对象都是“被引用的”(ref'ed),因此通常不需要调用 watcher.ref()
,除非之前调用了 watcher.unref()
。
watcher.unref()
#
当调用时,活动的 <fs.FSWatcher> 对象将不要求 Node.js 事件循环保持活动状态。如果没有其他活动使事件循环运行,进程可能会在 <fs.FSWatcher> 对象的回调被调用之前退出。多次调用 watcher.unref()
将没有效果。
类: fs.StatWatcher
#
- 继承自 <EventEmitter>
成功调用 fs.watchFile()
方法将返回一个新的 <fs.StatWatcher> 对象。
watcher.ref()
#
- 返回: <fs.StatWatcher>
当调用时,请求 Node.js 事件循环只要 <fs.StatWatcher> 处于活动状态就*不要*退出。多次调用 watcher.ref()
将没有效果。
默认情况下,所有 <fs.StatWatcher> 对象都是“被引用的”(ref'ed),因此通常不需要调用 watcher.ref()
,除非之前调用了 watcher.unref()
。
watcher.unref()
#
- 返回: <fs.StatWatcher>
当调用时,活动的 <fs.StatWatcher> 对象将不要求 Node.js 事件循环保持活动状态。如果没有其他活动使事件循环运行,进程可能会在 <fs.StatWatcher> 对象的回调被调用之前退出。多次调用 watcher.unref()
将没有效果。
类: fs.ReadStream
#
- 继承自: <stream.Readable>
<fs.ReadStream> 的实例是使用 fs.createReadStream()
函数创建并返回的。
事件: 'close'
#
当 <fs.ReadStream> 的底层文件描述符被关闭时发出。
类: fs.Stats
#
一个 <fs.Stats> 对象提供有关文件的信息。
从 fs.stat()
、fs.lstat()
、fs.fstat()
及其同步对应方法返回的对象都属于此类型。如果传递给这些方法的 options
中的 bigint
为 true,则数值将是 bigint
而不是 number
,并且对象将包含以 Ns
为后缀的额外纳秒精度属性。不应直接使用 new
关键字创建 Stat
对象。
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
bigint
版本
BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
stats.isDirectory()
#
- 返回:<boolean>
如果 <fs.Stats> 对象描述了一个文件系统目录,则返回 true
。
如果 <fs.Stats> 对象是通过对解析为目录的符号链接调用 fs.lstat()
获得的,此方法将返回 false
。这是因为 fs.lstat()
返回的是关于符号链接本身的信息,而不是它解析到的路径信息。
Stat 时间值#
atimeMs
、mtimeMs
、ctimeMs
、birthtimeMs
属性是保存相应时间(以毫秒为单位)的数值。它们的精度是平台特定的。当生成该对象的方法中传入 bigint: true
时,这些属性将是 bigints,否则它们将是 numbers。
atimeNs
、mtimeNs
、ctimeNs
、birthtimeNs
属性是保存相应时间(以纳秒为单位)的 bigints。它们仅当生成该对象的方法中传入 bigint: true
时才存在。它们的精度是平台特定的。
atime
、mtime
、ctime
和 birthtime
是各种时间的 Date
对象替代表示。Date
和数值是不相连的。分配一个新的数值,或修改 Date
值,都不会反映在相应的替代表示中。
stat 对象中的时间具有以下语义:
atime
“访问时间”:文件数据最后被访问的时间。由mknod(2)
、utimes(2)
和read(2)
系统调用更改。mtime
“修改时间”:文件数据最后被修改的时间。由mknod(2)
、utimes(2)
和write(2)
系统调用更改。ctime
"Change Time":文件状态上次更改的时间(inode 数据修改)。chmod(2)
、chown(2)
、link(2)
、mknod(2)
、rename(2)
、unlink(2)
、utimes(2)
、read(2)
和write(2)
系统调用会更改此时间。birthtime
"Birth Time":文件创建的时间。在文件创建时设置一次。在文件系统不支持 `birthtime` 的情况下,此字段可能会保存 `ctime` 或 `1970-01-01T00:00Z`(即 Unix 纪元时间戳 `0`)。在这种情况下,此值可能大于 `atime` 或 `mtime`。在 Darwin 和其他 FreeBSD 变体上,如果使用utimes(2)
系统调用将 `atime` 显式设置为比当前 `birthtime` 更早的值,则也会设置此时间。
在 Node.js 0.12 之前,Windows 系统上的 `ctime` 表示 `birthtime`。自 0.12 版本起,`ctime` 不再是“创建时间”,并且在 Unix 系统上,它从来都不是。
类:fs.StatFs
#
提供有关已挂载文件系统的信息。
从 fs.statfs()
及其同步对应方法返回的对象属于此类型。如果传递给这些方法的 `options` 中的 `bigint` 为 `true`,则数值将是 `bigint` 而不是 `number`。
StatFs {
type: 1397114950,
bsize: 4096,
blocks: 121938943,
bfree: 61058895,
bavail: 61058895,
files: 999,
ffree: 1000000
}
bigint
版本
StatFs {
type: 1397114950n,
bsize: 4096n,
blocks: 121938943n,
bfree: 61058895n,
bavail: 61058895n,
files: 999n,
ffree: 1000000n
}
类:fs.Utf8Stream
#
一个优化的 UTF-8 流写入器,允许按需刷新所有内部缓冲。它能正确处理 `EAGAIN` 错误,并允许自定义行为,例如在磁盘繁忙时丢弃内容。
事件:'close'
#
当流完全关闭时,会触发 'close'
事件。
事件:'drain'
#
当内部缓冲区已充分排空以允许继续写入时,会触发 'drain'
事件。
事件:'drop'
#
当达到最大长度且数据将不会被写入时,会触发 'drop'
事件。被丢弃的数据将作为第一个参数传递给事件句柄。
事件:'error'
#
当发生错误时,会触发 'error'
事件。
事件:'finish'
#
当流已结束并且所有数据都已刷新到底层文件时,会触发 'finish'
事件。
事件:'ready'
#
当流准备好接受写入时,会触发 'ready'
事件。
事件:'write'
#
当一次写入操作完成时,会触发 'write'
事件。写入的字节数将作为第一个参数传递给事件处理程序。
new fs.Utf8Stream([options])
#
options
<Object>append
: <boolean> 将写入内容追加到目标文件,而不是截断它。默认值:true
。contentMode
: <string> 您可以发送给 write 函数的数据类型,支持的值为'utf8'
或'buffer'
。默认值:'utf8'
。dest
: <string> 要写入的文件的路径(模式由 append 选项控制)。fd
: <number> 文件描述符,由fs.open()
或fs.openSync()
返回。fs
: <Object> 一个具有与 `fs` 模块相同 API 的对象,可用于模拟、测试或自定义流的行为。fsync
: <boolean> 每次写入完成后执行一次fs.fsyncSync()
。maxLength
: <number> 内部缓冲区的最大长度。如果一次写入操作会导致缓冲区超过 `maxLength`,则写入的数据将被丢弃,并触发一个带有被丢弃数据的 `drop` 事件。maxWrite
: <number> 可以写入的最大字节数;默认值:16384
minLength
: <number> 在刷新之前,内部缓冲区需要被填满的最小长度。mkdir
: <boolean> 当为 `true` 时,确保 `dest` 文件的目录存在。默认值:false
。mode
: <number> | <string> 指定创建文件的模式(参见 `fs.open()`)。periodicFlush
: <number> 每隔 `periodicFlush` 毫秒调用一次 `flush`。retryEAGAIN
<Function> 当write()
、writeSync()
或flushSync()
遇到 `EAGAIN` 或 `EBUSY` 错误时将调用的函数。如果返回值为 `true`,操作将被重试,否则将抛出错误。`err` 是导致此函数被调用的错误,`writeBufferLen` 是被写入的缓冲区长度,`remainingBufferLen` 是流未尝试写入的剩余缓冲区长度。sync
: <boolean> 同步执行写入操作。
utf8Stream.destroy()
#
立即关闭流,不刷新内部缓冲区。
utf8Stream.end()
#
平稳地关闭流,在关闭前刷新内部缓冲区。
utf8Stream.flush(callback)
#
callback
<Function>
如果当前没有写入操作在进行中,则将当前缓冲区写入文件。如果 `minLength` 为零或已经在写入,则不执行任何操作。
utf8Stream.flushSync()
#
同步刷新缓冲的数据。这是一个耗费资源的操作。
utf8Stream.maxLength
#
- <number> 内部缓冲区的最大长度。如果一次写入操作会导致缓冲区超过 `maxLength`,则写入的数据将被丢弃,并触发一个带有被丢弃数据的 `drop` 事件。
utf8Stream.reopen(file)
#
就地重新打开文件,对日志轮换很有用。
utf8Stream.write(data)
#
当创建流时 `options.contentMode` 设置为 `utf8` 时,`data` 参数必须是字符串。如果 `contentMode` 设置为 `buffer`,`data` 参数必须是 <Buffer>。
utf8Stream[Symbol.dispose]()
#
调用 utf8Stream.destroy()
。
类:fs.WriteStream
#
<fs.WriteStream> 的实例是使用 fs.createWriteStream()
函数创建并返回的。
事件:'close'
#
当 <fs.WriteStream> 的底层文件描述符被关闭时触发。
writeStream.bytesWritten
#
到目前为止已写入的字节数。不包括仍在排队等待写入的数据。
writeStream.close([callback])
#
callback
<Function>err
<Error>
关闭 writeStream
。可选地接受一个回调函数,该函数将在 writeStream
关闭后执行。
writeStream.path
#
流正在写入的文件的路径,该路径在 fs.createWriteStream()
的第一个参数中指定。如果 `path` 以字符串形式传递,则 `writeStream.path` 将是一个字符串。如果 `path` 以 <Buffer> 形式传递,则 `writeStream.path` 将是一个 <Buffer>。
fs.constants
#
- 类型:<Object>
返回一个包含文件系统操作常用常量的对象。
FS 常量#
以下常量由 `fs.constants` 和 `fsPromises.constants` 导出。
并非所有常量在每个操作系统上都可用;这对于 Windows 尤其重要,因为许多 POSIX 特定的定义在 Windows 上不可用。对于可移植的应用程序,建议在使用前检查它们是否存在。
要使用多个常量,请使用按位或 `|` 运算符。
示例
import { open, constants } from 'node:fs';
const {
O_RDWR,
O_CREAT,
O_EXCL,
} = constants;
open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
// ...
});
文件访问常量#
以下常量旨在用作传递给 fsPromises.access()
、fs.access()
和 fs.accessSync()
的 `mode` 参数。
常量 | 描述 |
---|---|
F_OK |
表示文件对调用进程可见的标志。这对于确定文件是否存在很有用,但对 `rwx` 权限没有任何说明。如果未指定模式,则为默认值。 |
R_OK |
表示文件可被调用进程读取的标志。 |
W_OK |
表示文件可被调用进程写入的标志。 |
X_OK |
表示文件可被调用进程执行的标志。在 Windows 上无效(行为类似于 `fs.constants.F_OK`)。 |
这些定义在 Windows 上也可用。
文件复制常量#
以下常量旨在与 fs.copyFile()
一起使用。
常量 | 描述 |
---|---|
COPYFILE_EXCL |
如果存在,当目标路径已存在时,复制操作将失败并返回错误。 |
COPYFILE_FICLONE |
如果存在,复制操作将尝试创建写时复制(copy-on-write)的 reflink。如果底层平台不支持写时复制,则会使用备用的复制机制。 |
COPYFILE_FICLONE_FORCE |
如果存在,复制操作将尝试创建写时复制(copy-on-write)的 reflink。如果底层平台不支持写时复制,则操作将失败并返回错误。 |
这些定义在 Windows 上也可用。
文件打开常量#
以下常量旨在与 `fs.open()` 一起使用。
常量 | 描述 |
---|---|
O_RDONLY |
表示以只读方式打开文件的标志。 |
O_WRONLY |
表示以只写方式打开文件的标志。 |
O_RDWR |
表示以读写方式打开文件的标志。 |
O_CREAT |
表示如果文件不存在则创建文件的标志。 |
O_EXCL |
表示如果设置了 `O_CREAT` 标志且文件已存在,则打开文件应失败的标志。 |
O_NOCTTY |
表示如果路径标识了一个终端设备,打开该路径不会导致该终端成为进程的控制终端(如果进程尚无控制终端)的标志。 |
O_TRUNC |
表示如果文件存在且为常规文件,并且文件成功以写权限打开,其长度将被截断为零的标志。 |
O_APPEND |
表示数据将被追加到文件末尾的标志。 |
O_DIRECTORY |
表示如果路径不是目录,则打开操作应失败的标志。 |
O_NOATIME |
表示对文件系统的读取访问将不再导致与文件关联的 `atime` 信息更新的标志。此标志仅在 Linux 操作系统上可用。 |
O_NOFOLLOW |
表示如果路径是符号链接,则打开操作应失败的标志。 |
O_SYNC |
表示文件以同步 I/O 方式打开,写操作会等待文件完整性的标志。 |
O_DSYNC |
表示文件以同步 I/O 方式打开,写操作会等待数据完整性的标志。 |
O_SYMLINK |
表示打开符号链接本身而不是它指向的资源的标志。 |
O_DIRECT |
设置时,将尝试最小化文件 I/O 的缓存效果。 |
O_NONBLOCK |
表示在可能的情况下以非阻塞模式打开文件的标志。 |
UV_FS_O_FILEMAP |
设置时,使用内存文件映射来访问文件。此标志仅在 Windows 操作系统上可用。在其他操作系统上,此标志被忽略。 |
在 Windows 上,只有 `O_APPEND`、`O_CREAT`、`O_EXCL`、`O_RDONLY`、`O_RDWR`、`O_TRUNC`、`O_WRONLY` 和 `UV_FS_O_FILEMAP` 可用。
文件类型常量#
以下常量旨在与 <fs.Stats> 对象的 `mode` 属性一起使用,以确定文件类型。
常量 | 描述 |
---|---|
S_IFMT |
用于提取文件类型代码的位掩码。 |
S_IFREG |
常规文件的文件类型常量。 |
S_IFDIR |
目录的文件类型常量。 |
S_IFCHR |
面向字符的设备文件的文件类型常量。 |
S_IFBLK |
面向块的设备文件的文件类型常量。 |
S_IFIFO |
FIFO/管道的文件类型常量。 |
S_IFLNK |
符号链接的文件类型常量。 |
S_IFSOCK |
套接字的文件类型常量。 |
在 Windows 上,只有 `S_IFCHR`、`S_IFDIR`、`S_IFLNK`、`S_IFMT` 和 `S_IFREG` 可用。
文件模式常量#
以下常量旨在与 <fs.Stats> 对象的 `mode` 属性一起使用,以确定文件的访问权限。
常量 | 描述 |
---|---|
S_IRWXU |
文件模式,表示所有者可读、可写和可执行。 |
S_IRUSR |
文件模式,表示所有者可读。 |
S_IWUSR |
文件模式,表示所有者可写。 |
S_IXUSR |
文件模式,表示所有者可执行。 |
S_IRWXG |
文件模式,表示组可读、可写和可执行。 |
S_IRGRP |
文件模式,表示组可读。 |
S_IWGRP |
文件模式,表示组可写。 |
S_IXGRP |
文件模式,表示组可执行。 |
S_IRWXO |
文件模式,表示其他人可读、可写和可执行。 |
S_IROTH |
文件模式,表示其他人可读。 |
S_IWOTH |
文件模式,表示其他人可写。 |
S_IXOTH |
文件模式,表示其他人可执行。 |
在 Windows 上,只有 `S_IRUSR` 和 `S_IWUSR` 可用。
说明#
基于回调和 Promise 的操作顺序#
因为它们由底层线程池异步执行,所以无论是使用基于回调还是基于 Promise 的方法,都无法保证执行顺序。
例如,以下代码容易出错,因为 `fs.stat()` 操作可能在 `fs.rename()` 操作之前完成。
const fs = require('node:fs');
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
通过等待一个操作的结果再调用另一个操作来正确排序操作是很重要的。
import { rename, stat } from 'node:fs/promises';
const oldPath = '/tmp/hello';
const newPath = '/tmp/world';
try {
await rename(oldPath, newPath);
const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
}
const { rename, stat } = require('node:fs/promises');
(async function(oldPath, newPath) {
try {
await rename(oldPath, newPath);
const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello', '/tmp/world');
或者,在使用回调 API 时,将 `fs.stat()` 调用移动到 `fs.rename()` 操作的回调中。
import { rename, stat } from 'node:fs';
rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
const { rename, stat } = require('node:fs/promises');
rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
文件路径#
大多数 `fs` 操作接受文件路径,这些路径可以以字符串、<Buffer> 或使用 `file:` 协议的 <URL> 对象的形式指定。
字符串路径#
字符串路径被解释为标识绝对或相对文件名的 UTF-8 字符序列。相对路径将相对于通过调用 `process.cwd()` 确定的当前工作目录进行解析。
在 POSIX 上使用绝对路径的示例
import { open } from 'node:fs/promises';
let fd;
try {
fd = await open('/open/some/file.txt', 'r');
// Do something with the file
} finally {
await fd?.close();
}
在 POSIX 上使用相对路径的示例(相对于 `process.cwd()`)
import { open } from 'node:fs/promises';
let fd;
try {
fd = await open('file.txt', 'r');
// Do something with the file
} finally {
await fd?.close();
}
文件 URL 路径#
对于大多数 `node:fs` 模块函数,`path` 或 `filename` 参数可以作为使用 `file:` 协议的 <URL> 对象传递。
import { readFileSync } from 'node:fs';
readFileSync(new URL('file:///tmp/hello'));
file:
URL 始终是绝对路径。
平台特定注意事项#
在 Windows 上,带有主机名的 `file:` <URL> 会转换为 UNC 路径,而带有驱动器盘符的 `file:` <URL> 会转换为本地绝对路径。没有主机名和驱动器盘符的 `file:` <URL> 将导致错误。
import { readFileSync } from 'node:fs';
// On Windows :
// - WHATWG file URLs with hostname convert to UNC path
// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
readFileSync(new URL('file://hostname/p/a/t/h/file'));
// - WHATWG file URLs with drive letters convert to absolute path
// file:///C:/tmp/hello => C:\tmp\hello
readFileSync(new URL('file:///C:/tmp/hello'));
// - WHATWG file URLs without hostname must have a drive letters
readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
readFileSync(new URL('file:///c/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
带有驱动器盘符的 `file:` <URL> 必须在驱动器盘符后使用 `:` 作为分隔符。使用其他分隔符将导致错误。
在所有其他平台上,不支持带有主机名的 `file:` <URL>,并将导致错误。
import { readFileSync } from 'node:fs';
// On other platforms:
// - WHATWG file URLs with hostname are unsupported
// file://hostname/p/a/t/h/file => throw!
readFileSync(new URL('file://hostname/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
// - WHATWG file URLs convert to absolute path
// file:///tmp/hello => /tmp/hello
readFileSync(new URL('file:///tmp/hello'));
在所有平台上,包含编码斜杠字符的 `file:` <URL> 将导致错误。
import { readFileSync } from 'node:fs';
// On Windows
readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */
// On POSIX
readFileSync(new URL('file:///p/a/t/h/%2F'));
readFileSync(new URL('file:///p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
/ characters */
在 Windows 上,包含编码反斜杠的 `file:` <URL> 将导致错误。
import { readFileSync } from 'node:fs';
// On Windows
readFileSync(new URL('file:///C:/path/%5C'));
readFileSync(new URL('file:///C:/path/%5c'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */
Buffer 路径#
使用 <Buffer> 指定的路径主要在某些将文件路径视为不透明字节序列的 POSIX 操作系统上有用。在此类系统上,单个文件路径可能包含使用多种字符编码的子序列。与字符串路径一样,<Buffer> 路径可以是相对的或绝对的。
在 POSIX 上使用绝对路径的示例
import { open } from 'node:fs/promises';
import { Buffer } from 'node:buffer';
let fd;
try {
fd = await open(Buffer.from('/open/some/file.txt'), 'r');
// Do something with the file
} finally {
await fd?.close();
}
文件描述符#
在 POSIX 系统上,对于每个进程,内核都维护一个当前打开的文件和资源的表。每个打开的文件都被分配一个简单的数字标识符,称为*文件描述符*。在系统级别,所有文件系统操作都使用这些文件描述符来识别和跟踪每个特定的文件。Windows 系统使用一种不同但概念上相似的机制来跟踪资源。为了简化用户的操作,Node.js 抽象了操作系统之间的差异,并为所有打开的文件分配一个数字文件描述符。
基于回调的 `fs.open()` 和同步的 `fs.openSync()` 方法会打开一个文件并分配一个新的文件描述符。一旦分配,文件描述符就可用于从文件读取数据、向文件写入数据或请求有关文件的信息。
操作系统限制了任何给定时间可能打开的文件描述符的数量,因此在操作完成后关闭描述符至关重要。否则将导致内存泄漏,最终导致应用程序崩溃。
import { open, close, fstat } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('/open/some/file.txt', 'r', (err, fd) => {
if (err) throw err;
try {
fstat(fd, (err, stat) => {
if (err) {
closeFd(fd);
throw err;
}
// use stat
closeFd(fd);
});
} catch (err) {
closeFd(fd);
throw err;
}
});
基于 Promise 的 API 使用 <FileHandle> 对象代替数字文件描述符。这些对象由系统更好地管理,以确保不会泄漏资源。但是,在操作完成后仍然需要关闭它们。
import { open } from 'node:fs/promises';
let file;
try {
file = await open('/open/some/file.txt', 'r');
const stat = await file.stat();
// use stat
} finally {
await file.close();
}
线程池的使用#
所有基于回调和 Promise 的文件系统 API(除了 `fs.FSWatcher()`)都使用 libuv 的线程池。这可能会对某些应用程序产生意想不到的负面性能影响。有关更多信息,请参阅 UV_THREADPOOL_SIZE
文档。
文件系统标志#
在 `flag` 选项接受字符串的任何地方,以下标志都可用。
-
'a'
:打开文件用于追加。如果文件不存在,则创建文件。 -
'ax'
:与'a'
类似,但如果路径存在则失败。 -
'a+'
:打开文件用于读取和追加。如果文件不存在,则创建文件。 -
'ax+'
:与'a+'
类似,但如果路径存在则失败。 -
'as'
:以同步模式打开文件用于追加。如果文件不存在,则创建文件。 -
'as+'
:以同步模式打开文件用于读取和追加。如果文件不存在,则创建文件。 -
'r'
:打开文件用于读取。如果文件不存在,则发生异常。 -
'rs'
:以同步模式打开文件用于读取。如果文件不存在,则发生异常。 -
'r+'
:打开文件用于读取和写入。如果文件不存在,则发生异常。 -
'rs+'
:以同步模式打开文件用于读取和写入。指示操作系统绕过本地文件系统缓存。这主要用于打开 NFS 挂载上的文件,因为它允许跳过可能过时的本地缓存。它对 I/O 性能有非常实际的影响,因此除非需要,否则不建议使用此标志。
这不会将 `fs.open()` 或 `fsPromises.open()` 变成同步阻塞调用。如果需要同步操作,应使用类似 `fs.openSync()` 的方法。
-
'w'
:打开文件用于写入。文件被创建(如果不存在)或截断(如果存在)。 -
'wx'
:与'w'
类似,但如果路径存在则失败。 -
'w+'
:打开文件用于读取和写入。文件被创建(如果不存在)或截断(如果存在)。 -
'wx+'
:与'w+'
类似,但如果路径存在则失败。
flag
也可以是 open(2)
文档中记录的数字;常用的常量可从 `fs.constants` 获得。在 Windows 上,标志会转换为其适用的等效项,例如 `O_WRONLY` 转换为 `FILE_GENERIC_WRITE`,或 `O_EXCL|O_CREAT` 转换为 `CREATE_NEW`,这些都是 `CreateFileW` 接受的。
排他标志 'x'
(open(2)
中的 `O_EXCL` 标志)会导致操作在路径已存在时返回错误。在 POSIX 上,如果路径是符号链接,即使链接指向不存在的路径,使用 `O_EXCL` 也会返回错误。排他标志可能不适用于网络文件系统。
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据附加到文件末尾。
修改文件而不是替换它可能需要将 `flag` 选项设置为 `r+` 而不是默认的 `w`。
某些标志的行为是特定于平台的。因此,在 macOS 和 Linux 上使用 `a+` 标志打开目录(如下例所示)将返回错误。相反,在 Windows 和 FreeBSD 上,将返回文件描述符或 `FileHandle`。
// macOS and Linux
fs.open('<directory>', 'a+', (err, fd) => {
// => [Error: EISDIR: illegal operation on a directory, open <directory>]
});
// Windows and FreeBSD
fs.open('<directory>', 'a+', (err, fd) => {
// => null, <fd>
});
在 Windows 上,使用 `w` 标志(通过 `fs.open()`、`fs.writeFile()` 或 `fsPromises.open()`)打开现有的隐藏文件将失败并返回 `EPERM`。可以使用 `r+` 标志打开现有的隐藏文件进行写入。
可以调用 `fs.ftruncate()` 或 `filehandle.truncate()` 来重置文件内容。