Node.js v20.20.6 文档


文件系统#>

【File system】

源代码: lib/fs.js

node:fs 模块允许以类似标准 POSIX 函数的方式与文件系统进行交互。

【The node:fs module enables interacting with the file system in a way modeled on standard POSIX functions.】

要使用基于 promise 的 API:

【To use the promise-based APIs:】

import * as fs from 'node:fs/promises';const fs = require('node:fs/promises');

要使用回调和同步的 API:

【To use the callback and sync APIs:】

import * as fs from 'node:fs';const fs = require('node:fs');

所有文件系统操作都有同步、回调和基于 Promise 的形式,并且可以通过 CommonJS 语法和 ES6 模块(ESM)访问。

【All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).】

Promise 示例#>

【Promise example】

基于 Promise 的操作会返回一个 Promise,当异步操作完成时,该 Promise 会被兑现。

【Promise-based operations return a promise that is fulfilled when the asynchronous operation is complete.】

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');

回调示例#>

【Callback example】

回调函数表单将完成回调函数作为其最后一个参数,并异步调用操作。传递给完成回调的参数取决于方法,但第一个参数始终保留给异常。如果操作成功完成,则第一个参数为 nullundefined

【The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument is null or 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 更为可取。

【The callback-based versions of the node:fs module APIs are preferable over the use of the promise APIs when maximal performance (both in terms of execution time and memory allocation) is required.】

同步示例#>

【Synchronous example】

同步 API 会阻塞 Node.js 的事件循环和后续的 JavaScript 执行,直到操作完成。异常会立即抛出,可以使用 try…catch 进行处理,或者允许异常向上冒泡。

【The synchronous APIs block the Node.js event loop and further JavaScript execution until the operation is complete. Exceptions are thrown immediately and can be handled using try…catch, or can be allowed to bubble up.】

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
}

Promise API#>

【Promises API】

fs/promises API 提供返回 promise 的异步文件系统方法。

【The fs/promises API provides asynchronous file system methods that return promises.】

Promise API 使用底层的 Node.js 线程池在事件循环线程之外执行文件系统操作。这些操作不是同步的,也不是线程安全的。在对同一个文件进行多次并发修改时必须小心,否则可能会导致数据损坏。

【The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.】

类:FileHandle#>

【Class: FileHandle

<FileHandle> 对象是用于数字文件描述符的对象封装器。

【A <FileHandle> object is an object wrapper for a numeric file descriptor.】

fsPromises.open() 方法会创建 <FileHandle> 对象的实例。

【Instances of the <FileHandle> object are created by the fsPromises.open() method.】

所有 <FileHandle> 对象都是 <EventEmitter>

【All <FileHandle> objects are <EventEmitter>s.】

如果 <FileHandle> 没有使用 filehandle.close() 方法关闭,它会尝试自动关闭文件描述符并发出进程警告,从而帮助防止内存泄漏。请不要依赖此行为,因为它可能不可靠,文件可能无法关闭。相反,应始终显式关闭 <FileHandle>。Node.js 未来可能会更改此行为。

【If a <FileHandle> is not closed using the filehandle.close() method, it will try to automatically close the file descriptor and emit a process warning, helping to prevent memory leaks. Please do not rely on this behavior because it can be unreliable and the file may not be closed. Instead, always explicitly close <FileHandle>s. Node.js may change this behavior in the future.】

事件:'close'#>

【Event: 'close'

<FileHandle> 已被关闭且无法再使用时,会触发 'close' 事件。

【The 'close' event is emitted when the <FileHandle> has been closed and can no longer be used.】

filehandle.appendFile(data[, options])#>

filehandle.writeFile() 的别名。

【Alias of filehandle.writeFile().】

在操作文件句柄时,模式不能从使用 fsPromises.open() 设置的状态更改。因此,这相当于 filehandle.writeFile()

【When operating on file handles, the mode cannot be changed from what it was set to with fsPromises.open(). Therefore, this is equivalent to filehandle.writeFile().】

filehandle.chmod(mode)#>

修改文件的权限。参见 chmod(2)

【Modifies the permissions on the file. See chmod(2).】

filehandle.chown(uid, gid)#>
  • uid <integer> 文件新所有者的用户ID。
  • gid <integer> 文件的新组的组ID。
  • 返回:<Promise> 成功时返回 undefined

更改文件的所有权。chown(2) 的封装。

【Changes the ownership of the file. A wrapper for chown(2).】

filehandle.close()#>
  • 返回:<Promise> 成功时返回 undefined

在等待与该句柄相关的任何待处理操作完成后关闭文件句柄。

【Closes the file handle after waiting for any pending operation on the handle to complete.】

import { open } from 'node:fs/promises';

let filehandle;
try {
  filehandle = await open('thefile.txt', 'r');
} finally {
  await filehandle?.close();
} 
filehandle.createReadStream([options])#>

options 可以包含 startend 值,用于读取以下范围内的字节是文件而不是整个文件。startend 都是包容性的, 从0开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围。如果 start 是 省略或 undefinedfs.createReadStream() 顺序读取于 当前文件位置。encoding 可以是以下任何一种被接受的 <Buffer>

如果 FileHandle 指向一个只支持阻塞读取的字符设备(例如键盘或声卡),读取操作将不会完成,直到有数据可用。这可能会阻止进程退出并使流无法自然关闭。

【If the FileHandle points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.】

默认情况下,流在被销毁后会触发 'close' 事件。将 emitClose 选项设置为 false 可以更改此行为。

【By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.】

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' 时文件描述符将会自动关闭。

【If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.】

读取 100 个字节长的文件的最后 10 个字节的示例:

【An example to read the last 10 bytes of a file which is 100 bytes long:】

import { open } from 'node:fs/promises';

const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 }); 
filehandle.createWriteStream([options])#>

options 也可以包含一个 start 选项,以允许在文件开头之后的某个位置写入数据,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围内。修改文件而不是替换文件可能需要将 flags open 选项设置为 r+,而不是默认的 rencoding 可以是 <Buffer> 接受的任何一种编码。

如果在 'error''finish' 上将 autoClose 设置为 true(默认行为),文件描述符将会自动关闭。如果 autoClose 为 false,即使发生错误,文件描述符也不会关闭。由应用负责关闭它,并确保不会发生文件描述符泄漏。

【If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.】

默认情况下,流在被销毁后会触发 'close' 事件。将 emitClose 选项设置为 false 可以更改此行为。

【By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.】

filehandle.datasync()#>
  • 返回:<Promise> 成功时返回 undefined

将当前排队的所有与文件相关的 I/O 操作强制写入操作系统的同步 I/O 完成状态。有关详细信息,请参阅 POSIX fdatasync(2) 文档。

【Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details.】

filehandle.sync 不同,此方法不会刷新已修改的元数据。

【Unlike filehandle.sync this method does not flush modified metadata.】

filehandle.fd#>
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> 成功时返回一个包含两个属性的对象:

从文件中读取数据,并将其存储在给定的缓冲区中。

【Reads data from the file and stores that in the given buffer.】

如果文件没有被同时修改,当读取的字节数为零时,就到达了文件末尾。

【If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.】

filehandle.read([options])#>
  • options <Object>
    • buffer <Buffer> | <TypedArray> | <DataView> 一个将被填充读取文件数据的缓冲区。默认值: Buffer.alloc(16384)
    • offset <integer> 开始填充的缓冲区位置。 默认值: 0
    • length <integer> 要读取的字节数。默认值: buffer.byteLength - offset
    • position <integer> | <null> 开始从文件读取数据的位置。如果为 null,数据将从当前文件位置读取,并且位置会被更新。如果 position 是整数,当前文件位置将保持不变。默认值: null
  • 返回:<Promise> 成功时返回一个包含两个属性的对象:

从文件中读取数据,并将其存储在给定的缓冲区中。

【Reads data from the file and stores that in the given buffer.】

如果文件没有被同时修改,当读取的字节数为零时,就到达了文件末尾。

【If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.】

filehandle.read(buffer[, options])#>
  • buffer <Buffer> | <TypedArray> | <DataView> 一个将被填充读取的文件数据的缓冲区。
  • options <Object>
    • offset <integer> 开始填充的缓冲区位置。 默认值: 0
    • length <integer> 要读取的字节数。默认值: buffer.byteLength - offset
    • position <integer> 开始从文件读取数据的位置。如果为 null,数据将从当前文件位置读取,同时位置会更新。如果 position 为整数,当前文件位置将保持不变。默认值: null
  • 返回:<Promise> 成功时返回一个包含两个属性的对象:

从文件中读取数据,并将其存储在给定的缓冲区中。

【Reads data from the file and stores that in the given buffer.】

如果文件没有被同时修改,当读取的字节数为零时,就到达了文件末尾。

【If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.】

filehandle.readableWebStream([options])#>

稳定性: 1 - 实验性

返回一个可用于读取文件数据的 ReadableStream

【Returns a ReadableStream that may be used to read the files data.】

如果此方法被调用超过一次,或者在 FileHandle 已关闭或正在关闭之后调用,将会抛出错误。

【An error will be thrown if this method is called more than once or is called after the FileHandle is closed or closing.】

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() 方法。

【While the ReadableStream will read the file to completion, it will not close the FileHandle automatically. User code must still call the fileHandle.close() method.】

filehandle.readFile(options)#>
  • options <Object> | <string>
  • 返回值:<Promise> 在成功读取文件内容时完成。如果未指定编码(使用 options.encoding),数据将以 <Buffer> 对象的形式返回。否则,数据将是一个字符串。

异步地读取文件的全部内容。

【Asynchronously reads the entire contents of a file.】

如果 options 是一个字符串,那么它指定了 encoding

【If options is a string, then it specifies the encoding.】

<FileHandle> 必须支持阅读。

【The <FileHandle> has to support reading.】

如果对一个文件句柄调用一次或多次 filehandle.read(),然后再调用 filehandle.readFile(),数据将从当前位置读取到文件末尾。它并不总是从文件开头开始读取。

【If one or more filehandle.read() calls are made on a file handle and then a filehandle.readFile() call is made, the data will be read from the current position till the end of the file. It doesn't always read from the beginning of the file.】

filehandle.readLines([options])#>

创建 readline 接口并对文件进行流式处理的便捷方法。有关选项,请参见 filehandle.createReadStream()

【Convenience method to create a readline interface and stream over the file. See filehandle.createReadStream() for the options.】

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])#>

从文件读取并写入到 <ArrayBufferView> 数组

【Read from a file and write to an array of <ArrayBufferView>s】

filehandle.stat([options])#>
filehandle.sync()#>
  • 返回:<Promise> 成功时返回 undefined

请求将所有打开文件描述符的数据刷新到存储设备。具体的实现取决于操作系统和设备。有关详细信息,请参考 POSIX fsync(2) 文档。

【Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail.】

filehandle.truncate(len)#>

截断文件。

【Truncates the file.】

如果文件大于 len 字节,文件中只会保留前 len 字节。

【If the file was larger than len bytes, only the first len bytes will be retained in the file.】

下面的示例仅保留文件的前四个字节:

【The following example retains only the first four bytes of the file:】

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''):

【If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):】

如果 len 为负数,则将使用 0

【If len is negative then 0 will be used.】

filehandle.utimes(atime, mtime)#>

更改 <FileHandle> 所引用对象的文件系统时间戳,成功时不带任何参数地完成承诺。

【Change the file system timestamps of the object referenced by the <FileHandle> then fulfills the promise with no arguments upon success.】

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 类型,数据将写入当前的位置。详情参见 POSIX pwrite(2) 文档。默认值: null
  • 返回:<Promise>

buffer 写入文件。

【Write buffer to the file.】

这个 promise 是通过一个包含两个属性的对象来实现的:

【The promise is fulfilled with an object containing two properties:】

在同一个文件上多次使用 filehandle.write() 是不安全的,如果不等待 Promise 被解决(或被拒绝)。对于这种情况,请使用 filehandle.createWriteStream()

【It is unsafe to use filehandle.write() multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use filehandle.createWriteStream().】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

filehandle.write(buffer[, options])#>

buffer 写入文件。

【Write buffer to the file.】

类似于上面的 filehandle.write 函数,这个版本也接受一个可选的 options 对象。如果没有指定 options 对象,它将使用上述默认值。

【Similar to the above filehandle.write function, this version takes an optional options object. If no options object is specified, it will default with the above values.】

filehandle.write(string[, position[, encoding]])#>
  • string <string>
  • position <integer> | <null> 从文件开头开始偏移的位置,string 中的数据应写入该位置。如果 position 不是 number 类型,则数据将写入当前的位置。详情参见 POSIX pwrite(2) 文档。默认值: null
  • encoding <string> 预期的字符串编码。默认值: 'utf8'
  • 返回:<Promise>

string 写入文件。如果 string 不是字符串,承诺将被拒绝并返回一个错误。

【Write string to the file. If string is not a string, the promise is rejected with an error.】

这个 promise 是通过一个包含两个属性的对象来实现的:

【The promise is fulfilled with an object containing two properties:】

  • bytesWritten <integer> 写入的字节数
  • buffer <string> 对已写入的 string 的引用。

在同一个文件上多次使用 filehandle.write() 是不安全的,如果不等待 Promise 被解决(或被拒绝)。对于这种情况,请使用 filehandle.createWriteStream()

【It is unsafe to use filehandle.write() multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use filehandle.createWriteStream().】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

filehandle.writeFile(data, options)#>

异步地将数据写入文件,如果文件已存在则替换它。data 可以是字符串、缓冲区、<AsyncIterable><Iterable> 对象。操作成功时,Promise 将不带任何参数地完成。

【Asynchronously writes data to a file, replacing the file if it already exists. data can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object. The promise is fulfilled with no arguments upon success.】

如果 options 是一个字符串,那么它指定了 encoding

【If options is a string, then it specifies the encoding.】

<FileHandle> 必须支持写入。

【The <FileHandle> has to support writing.】

在同一个文件上多次使用 filehandle.writeFile() 是不安全的,除非等待该 promise 被完成(或拒绝)。

【It is unsafe to use filehandle.writeFile() multiple times on the same file without waiting for the promise to be fulfilled (or rejected).】

如果对文件句柄执行一次或多次 filehandle.write() 调用,然后再进行 filehandle.writeFile() 调用,数据将从当前位置写入到文件末尾。它并不总是从文件开头写入。

【If one or more filehandle.write() calls are made on a file handle and then a filehandle.writeFile() call is made, the data will be written from the current position till the end of the file. It doesn't always write from the beginning of the file.】

filehandle.writev(buffers[, position])#>

<ArrayBufferView> 数组写入文件。

【Write an array of <ArrayBufferView>s to the file.】

这个 promise 是通过一个包含两个属性的对象来实现的:

【The promise is fulfilled with an object containing a two properties:】

在同一个文件上多次调用 writev() 而不等待 Promise 被完成(或拒绝)是不安全的。

【It is unsafe to call writev() multiple times on the same file without waiting for the promise to be fulfilled (or rejected).】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

filehandle[Symbol.asyncDispose]()#>

稳定性: 1 - 实验性

filehandle.close() 的别名。

【An alias for filehandle.close().】

fsPromises.access(path[, mode])#>

测试用户对由 path 指定的文件或目录的权限。 mode 参数是一个可选的整数,用于指定要执行的可访问性检查。mode 应为 fs.constants.F_OK 的值,或由 fs.constants.R_OKfs.constants.W_OKfs.constants.X_OK 中任意组合按位或计算得到的掩码(例如 fs.constants.W_OK | fs.constants.R_OK)。请查看 文件访问常量 以了解 mode 的可能取值。

【Tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g. fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.】

如果可访问性检查成功,Promise 将以无值的形式被实现。如果任何可访问性检查失败,Promise 将被一个 <Error> 对象拒绝。以下示例检查当前进程是否可以读取和写入文件 /etc/passwd

【If the accessibility check is successful, the promise is fulfilled with no value. If any of the accessibility checks fail, the promise is rejected with an <Error> object. The following example checks if the file /etc/passwd can be read and written by the current process.】

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() 来检查文件的可访问性是不推荐的。这会引入竞争条件,因为在两次调用之间,其他进程可能会改变文件的状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不可访问时产生的错误。

【Using fsPromises.access() to check for the accessibility of a file before calling fsPromises.open() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.】

fsPromises.appendFile(path, data[, options])#>

异步地向文件追加数据,如果文件尚不存在则创建该文件。data 可以是字符串或 <Buffer>

【Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a <Buffer>.】

如果 options 是一个字符串,那么它指定了 encoding

【If options is a string, then it specifies the encoding.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

path 可以指定为已打开以进行追加的 <FileHandle>(使用 fsPromises.open())。

【The path may be specified as a <FileHandle> that has been opened for appending (using fsPromises.open()).】

fsPromises.chmod(path, mode)#>

更改文件的权限。

【Changes the permissions of a file.】

fsPromises.chown(path, uid, gid)#>

更改文件的所有权。

【Changes the ownership of a file.】

fsPromises.copyFile(src, dest[, mode])#>

  • src <string> | <Buffer> | <URL> 要复制的源文件名
  • dest <string> | <Buffer> | <URL> 复制操作的目标文件名
  • mode <integer> 可选修饰符,用于指定复制操作的行为。可以创建一个由两个或更多值按位 OR 组成的掩码(例如 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 已经存在,会被覆盖。

【Asynchronously copies src to dest. By default, dest is overwritten if it already exists.】

无法保证复制操作的原子性。如果在目标文件已被打开以进行写入后发生错误,将尝试删除目标文件。

【No guarantees are made about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination.】

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])#>

稳定性: 1 - 实验性

  • src <string> | <URL> 要复制的源路径。
  • dest <string> | <URL> 复制到的目标路径。
  • options <Object>
    • dereference <boolean> 取消符号链接引用。默认值: false
    • errorOnExist <boolean>forcefalse 且目标已存在时,抛出错误。默认值: false
    • filter <Function> 用于筛选复制的文件/目录的函数。返回 true 表示复制该项,返回 false 表示忽略。当忽略一个目录时,其所有内容也将被跳过。也可以返回一个解析为 truefalsePromise默认值: undefined
      • src <string> 要复制的源路径。
      • dest <string> 复制到的目标路径。
      • 返回值:<boolean> | <Promise> 一个可以被强制转换为 boolean 的值,或者一个返回该值的 Promise
    • 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,包括子目录和文件。

【Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.】

将目录复制到另一个目录时,不支持通配符,行为类似于 cp dir1/ dir2/

【When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.】

fsPromises.lchmod(path, mode)#>

稳定性: 0 - 已弃用

更改符号链接的权限。

【Changes the permissions on a symbolic link.】

此方法仅在 macOS 上实现。

【This method is only implemented on macOS.】

fsPromises.lchown(path, uid, gid)#>

更改符号链接上的所有权。

【Changes the ownership on a symbolic link.】

fsPromises.lutimes(path, atime, mtime)#>

以与 fsPromises.utimes() 相同的方式更改文件的访问和修改时间,区别在于如果路径指向符号链接,则不会解除引用链接:相反,将更改符号链接本身的时间戳。

【Changes the access and modification times of a file in the same way as fsPromises.utimes(), with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.】

fsPromises.link(existingPath, newPath)#>

existingPathnewPath 之间创建一个新链接。有关详细信息,请参阅 POSIX link(2) 文档。

【Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail.】

fsPromises.lstat(path[, options])#>

等同于 fsPromises.stat(),除非 path 指向符号链接,在这种情况下,会对链接本身进行状态获取,而不是它指向的文件。更多细节请参考 POSIX lstat(2) 文档。

【Equivalent to fsPromises.stat() unless path refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX lstat(2) document for more detail.】

fsPromises.mkdir(path[, options])#>

异步地创建目录。

【Asynchronously creates a directory.】

可选的 options 参数可以是一个整数,指定 mode(权限和粘滞位),或者是一个包含 mode 属性和 recursive 属性的对象,recursive 属性用于指示是否应创建父目录。当 path 是已存在的目录时调用 fsPromises.mkdir(),仅在 recursive 为 false 时会导致拒绝。

【The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fsPromises.mkdir() when path is a directory that exists results in a rejection only when recursive is 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 后附加六个随机字符来生成唯一的目录名。由于平台差异,避免在 prefix 中使用尾随的 X 字符。一些平台,特别是 BSD 系统,可能会返回超过六个随机字符,并将 prefix 尾随的 X 字符替换为随机字符。

【Creates a unique temporary directory. A unique directory name is generated by appending six random characters to the end of the provided prefix. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.】

可选的 options 参数可以是指定编码的字符串,或者是一个具有 encoding 属性的对象,用于指定要使用的字符编码。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.】

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)结尾。

【The fsPromises.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within /tmp, the prefix must end with a trailing platform-specific path separator (require('node:path').sep).】

fsPromises.open(path, flags[, mode])#>

打开一个 <FileHandle>

【Opens a <FileHandle>.】

有关更多详细信息,请参阅 POSIX open(2) 文档。

【Refer to the POSIX open(2) documentation for more detail.】

在 Windows 系统下,一些字符(< > : " / \ | ? *)是保留的,如 命名文件、路径和命名空间 所述。在 NTFS 中,如果文件名包含冒号,Node.js 将会打开文件系统流,如 这个 MSDN 页面 所述。

【Some characters (< > : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.】

fsPromises.opendir(path[, options])#>

异步打开目录以进行迭代扫描。有关更多详细信息,请参阅 POSIX opendir(3) 文档。

【Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail.】

创建一个 <fs.Dir>,其中包含用于从目录中读取和清理的所有后续功能。

【Creates an <fs.Dir>, which contains all further functions for reading from and cleaning up the directory.】

encoding 选项用于设置在打开目录以及后续读取操作时 path 的编码。

【The encoding option sets the encoding for the path while opening the directory and subsequent read operations.】

使用异步迭代的示例:

【Example using async iteration:】

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> 对象将在迭代器退出后自动关闭。

【When using the async iterator, the <fs.Dir> object will be automatically closed after the iterator exits.】

fsPromises.readdir(path[, options])#>

  • path <string> | <Buffer> | <URL>
  • options <string> | <Object>
    • encoding <string> 默认值: 'utf8'
    • withFileTypes <boolean> 默认值: false
    • recursive <boolean> 如果为 true,将递归读取目录的内容。在递归模式下,它会列出所有文件、子文件和目录。默认值: false
  • 返回:<Promise>,以数组形式返回目录中除 '.''..' 之外的文件名。

读取目录的内容。

【Reads the contents of a directory.】

可选的 options 参数可以是指定编码的字符串,或者是包含 encoding 属性的对象,用于指定文件名的字符编码。如果 encoding 设置为 'buffer',返回的文件名将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames. If the encoding is set to 'buffer', the filenames returned will be passed as <Buffer> objects.】

如果 options.withFileTypes 设置为 true,返回的数组将包含 <fs.Dirent> 对象。

【If options.withFileTypes is set to true, the returned array will contain <fs.Dirent> objects.】

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])#>

异步地读取文件的全部内容。

【Asynchronously reads the entire contents of a file.】

如果未指定编码(使用 options.encoding),数据将作为 <Buffer> 对象返回。否则,数据将是一个字符串。

【If no encoding is specified (using options.encoding), the data is returned as a <Buffer> object. Otherwise, the data will be a string.】

如果 options 是字符串,那么它指定了编码。

【If options is a string, then it specifies the encoding.】

path 是一个目录时,fsPromises.readFile() 的行为取决于平台。在 macOS、Linux 和 Windows 上,Promise 会被拒绝并返回一个错误。在 FreeBSD 上,将返回该目录内容的表示。

【When the path is a directory, the behavior of fsPromises.readFile() is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned.】

在运行代码的同一目录中读取 package.json 文件的示例:

【An example of reading a package.json file located in the same directory of the running code:】

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 拒绝:

【It is possible to abort an ongoing readFile using an <AbortSignal>. If a request is aborted the promise returned is rejected with an 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 所执行的操作。

【Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.】

任何指定的 <FileHandle> 都必须支持读取。

【Any specified <FileHandle> has to support reading.】

fsPromises.readlink(path[, options])#>

读取由 path 指向的符号链接的内容。有关更多详细信息,请参阅 POSIX readlink(2) 文档。成功时,承诺将返回 linkString

【Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is fulfilled with the linkString upon success.】

可选的 options 参数可以是一个指定编码的字符串,或者是一个具有 encoding 属性的对象,该属性指定要用于返回的链接路径的字符编码。如果 encoding 设置为 'buffer',返回的链接路径将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a <Buffer> object.】

fsPromises.realpath(path[, options])#>

使用与 fs.realpath.native() 函数相同的语义来确定 path 的实际位置。

【Determines the actual location of path using the same semantics as the fs.realpath.native() function.】

仅支持可以转换为 UTF8 字符串的路径。

【Only paths that can be converted to UTF8 strings are supported.】

可选的 options 参数可以是指定编码的字符串,或者是具有 encoding 属性的对象,用于指定路径的字符编码。如果 encoding 设置为 'buffer',返回的路径将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path. If the encoding is set to 'buffer', the path returned will be passed as a <Buffer> object.】

在 Linux 上,当 Node.js 与 musl libc 链接时,必须将 procfs 文件系统挂载在 /proc 上,这样该函数才能工作。Glibc 没有这个限制。

【On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.】

fsPromises.rename(oldPath, newPath)#>

oldPath 重命名为 newPath

【Renames oldPath to newPath.】

fsPromises.rmdir(path[, options])#>

  • path <string> | <Buffer> | <URL>
  • options <Object>
    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 会以线性回退的方式重试操作,每次重试等待时间比上次增加 retryDelay 毫秒。此选项表示重试次数。如果 recursive 选项不是 true,此选项将被忽略。默认值: 0
    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作在失败时会重试。默认值: false已弃用。
    • retryDelay <integer> 重试之间等待的时间,以毫秒为单位。如果 recursive 选项不为 true,则此选项将被忽略。默认值: 100
  • 返回:<Promise> 成功时返回 undefined

删除由 path 指定的目录。

【Removes the directory identified by path.】

在文件(而不是目录)上使用 fsPromises.rmdir() 会导致在 Windows 上 Promise 被拒绝并返回 ENOENT 错误,而在 POSIX 上返回 ENOTDIR 错误。

【Using fsPromises.rmdir() on a file (not a directory) results in the promise being rejected with an ENOENT error on Windows and an ENOTDIR error on POSIX.】

要获得类似于 rm -rf Unix 命令的行为,请使用 fsPromises.rm(),并设置选项 { recursive: true, force: true }

【To get a behavior similar to the rm -rf Unix command, use fsPromises.rm() with options { recursive: true, force: true }.】

fsPromises.rm(path[, options])#>

  • path <string> | <Buffer> | <URL>
  • options <Object>
    • force <boolean> 当为 true 时,如果 path 不存在,将忽略异常。默认值: false
    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 将以线性回退方式重试操作,每次重试等待时间比上次增加 retryDelay 毫秒。此选项表示重试次数。如果 recursive 选项不是 true,此选项将被忽略。默认值: 0
    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作失败时会重试。默认值: false
    • retryDelay <integer> 重试之间等待的时间,以毫秒为单位。如果 recursive 选项不为 true,则此选项将被忽略。默认值: 100
  • 返回:<Promise> 成功时返回 undefined

删除文件和目录(基于标准 POSIX rm 工具)。

【Removes files and directories (modeled on the standard POSIX rm utility).】

fsPromises.stat(path[, options])#>

fsPromises.statfs(path[, options])#>

fsPromises.symlink(target, path[, type])#>

创建符号链接。

【Creates a symbolic link.】

type 参数仅在 Windows 平台上使用,可以是 'dir''file''junction'。如果 type 参数不是字符串,Node.js 会自动检测 target 的类型,并使用 'file''dir'。如果 target 不存在,将使用 'file'。Windows 联接点要求目标路径为绝对路径。使用 'junction' 时,target 参数会自动规范化为绝对路径。NTFS 卷上的联接点只能指向目录。

【The type argument is only used on Windows platforms and can be one of 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', the target argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.】

fsPromises.truncate(path[, len])#>

path 处的内容截断(缩短或延长长度)至 len 字节。

【Truncates (shortens or extends the length) of the content at path to len bytes.】

fsPromises.unlink(path)#>

如果 path 指向一个符号链接,则删除该链接而不影响该链接所指向的文件或目录。如果 path 指向一个非符号链接的文件路径,则删除该文件。更多详情请参阅 POSIX unlink(2) 文档。

【If path refers to a symbolic link, then the link is removed without affecting the file or directory to which that link refers. If the path refers to a file path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail.】

fsPromises.utimes(path, atime, mtime)#>

更改由 path 引用的对象的文件系统时间戳。

【Change the file system timestamps of the object referenced by path.】

atimemtime 参数遵循以下规则:

【The atime and mtime arguments follow these rules:】

  • 值可以是表示 Unix 纪元时间的数字、Date 对象,或者像 '123456789.0' 这样的数字字符串。
  • 如果该值无法转换为数字,或者是 NaNInfinity-Infinity,将会抛出一个 Error

fsPromises.watch(filename[, options])#>

返回一个异步迭代器,用于监视 filename 的变化,其中 filename 可以是文件或目录。

【Returns an async iterator that watches for changes on filename, where filename is either a file or a directory.】

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'

【On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.】

关于 fs.watch() 的所有 注意事项 也同样适用于 fsPromises.watch()

【All the caveats for fs.watch() also apply to fsPromises.watch().】

fsPromises.writeFile(file, data[, options])#>

异步将数据写入文件,如果文件已存在则替换。data 可以是字符串、缓冲区、<AsyncIterable><Iterable> 对象。

【Asynchronously writes data to a file, replacing the file if it already exists. data can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.】

如果 data 是缓冲区,则会忽略 encoding 选项。

【The encoding option is ignored if data is a buffer.】

如果 options 是字符串,那么它指定了编码。

【If options is a string, then it specifies the encoding.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

任何指定的 <FileHandle> 都必须支持写入。

【Any specified <FileHandle> has to support writing.】

在不等待 Promise 完成的情况下,多次使用 fsPromises.writeFile() 写入同一个文件是不安全的。

【It is unsafe to use fsPromises.writeFile() multiple times on the same file without waiting for the promise to be settled.】

fsPromises.readFile 类似,fsPromises.writeFile 是一个便捷方法,它内部执行多次 write 调用来写入传入的缓冲区。对于对性能敏感的代码,建议考虑使用 fs.createWriteStream()filehandle.createWriteStream()

【Similarly to fsPromises.readFile - fsPromises.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using fs.createWriteStream() or filehandle.createWriteStream().】

可以使用 <AbortSignal> 来取消 fsPromises.writeFile()。取消是“尽最大努力”的,有些数据仍可能会被写入。

【It is possible to use an <AbortSignal> to cancel an fsPromises.writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.】

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 执行的内部缓冲操作。

【Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs.】

fsPromises.constants#>

返回一个包含常用文件系统操作常量的对象。该对象与 fs.constants 相同。更多详情请参见 文件系统常量

【Returns an object containing commonly used constants for file system operations. The object is the same as fs.constants. See FS constants for more details.】

回调接口#>

【Callback API】

回调 API 以异步方式执行所有操作,不会阻塞事件循环,并在完成或出错时调用回调函数。

【The callback APIs perform all operations asynchronously, without blocking the event loop, then invoke a callback function upon completion or error.】

回调 API 使用底层的 Node.js 线程池在事件循环线程之外执行文件系统操作。这些操作不是同步的,也不是线程安全的。在对同一文件进行多个并发修改时必须小心,否则可能会导致数据损坏。

【The callback APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.】

fs.access(path[, mode], callback)#>

测试用户对由 path 指定的文件或目录的权限。 mode 参数是一个可选的整数,用于指定要执行的可访问性检查。mode 应为 fs.constants.F_OK 的值,或由 fs.constants.R_OKfs.constants.W_OKfs.constants.X_OK 中任意组合按位或计算得到的掩码(例如 fs.constants.W_OK | fs.constants.R_OK)。请查看 文件访问常量 以了解 mode 的可能取值。

【Tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g. fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.】

最后一个参数 callback 是一个回调函数,会在可能的错误参数下被调用。如果任何可访问性检查失败,错误参数将是一个 Error 对象。以下示例检查 package.json 是否存在,以及它是否可读或可写。

【The final argument, callback, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an Error object. The following examples check if package.json exists, and if it is readable or writable.】

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() 来检查文件的可访问性。这样做会引入竞争条件,因为其他进程可能在两次调用之间改变文件的状态。相反,用户代码应该直接打开/读取/写入文件,如果文件不可访问则处理引发的错误。

【Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile(), or fs.writeFile(). Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.】

写 (不推荐)

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;
    });
  }
}); 

上面的“不推荐”示例先检查可访问性然后再使用文件;“推荐”示例更好,因为它们直接使用文件,并处理可能出现的错误。

【The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.】

一般来说,只有在文件不会被直接使用时才检查其可访问性,例如当其可访问性是来自另一个进程的信号时。

【In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.】

在 Windows 上,目录的访问控制策略(ACL)可能会限制对文件或目录的访问。然而,fs.access() 函数不会检查 ACL,因此即使 ACL 限制用户读取或写入,它也可能报告某个路径是可访问的。

【On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The fs.access() function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.】

fs.appendFile(path, data[, options], callback)#>

异步地向文件追加数据,如果文件尚不存在则创建该文件。data 可以是字符串或 <Buffer>

【Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a <Buffer>.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

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 是字符串,则它指定了编码方式:

【If options is a string, then it specifies the encoding:】

import { appendFile } from 'node:fs';

appendFile('message.txt', 'data to append', 'utf8', callback); 

path 可以指定为已打开以便追加的数字文件描述符(使用 fs.open()fs.openSync())。该文件描述符不会自动关闭。

【The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.】

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)#>

异步更改文件的权限。完成回调不会提供除可能的异常以外的任何参数。

【Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX chmod(2) 文档。

【See the POSIX chmod(2) documentation for more detail.】

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!');
}); 

文件模式#>

【File modes】

fs.chmod()fs.chmodSync() 方法中使用的 mode 参数是一个数字位掩码,通过以下常量的逻辑或创建:

【The mode argument used in both the fs.chmod() and fs.chmodSync() methods is a numeric bitmask created using a logical OR of the following constants:】

常量八进制描述
fs.constants.S_IRUSR0o400拥有者可读
fs.constants.S_IWUSR0o200拥有者可写
fs.constants.S_IXUSR0o100拥有者可执行/搜索
fs.constants.S_IRGRP0o40组成员可读
fs.constants.S_IWGRP0o20组成员可写
fs.constants.S_IXGRP0o10组成员可执行/搜索
fs.constants.S_IROTH0o4其他人可读
fs.constants.S_IWOTH0o2其他人可写
fs.constants.S_IXOTH0o1其他人可执行/搜索

构造 mode 的一个更简单的方法是使用由三个八进制数字组成的序列(例如 765)。最左边的数字(在例子中是 7)指定文件所有者的权限。中间的数字(在例子中是 6)指定组的权限。最右边的数字(在例子中是 5)指定其他用户的权限。

【An easier method of constructing the mode is to use a sequence of three octal digits (e.g. 765). The left-most digit (7 in the example), specifies the permissions for the file owner. The middle digit (6 in the example), specifies permissions for the group. The right-most digit (5 in the example), specifies the permissions for others.】

数字描述
7读、写和执行
6读和写
5读和执行
4只读
3写和执行
2只写
1只执行
0无权限

例如,八进制值 0o765 表示:

【For example, the octal value 0o765 means:】

  • 文件所有者可以读取、写入和执行该文件。
  • 该组可以读取和写入该文件。
  • 其他人可以读取和执行该文件。

在期望使用文件模式的情况下使用原始数字时,任何大于 0o777 的值可能会导致平台特定的行为,这些行为无法保证一致。因此,像 S_ISVTXS_ISGIDS_ISUID 这样的常量在 fs.constants 中未被暴露。

【When using raw numbers where file modes are expected, any value larger than 0o777 may result in platform-specific behaviors that are not supported to work consistently. Therefore constants like S_ISVTX, S_ISGID, or S_ISUID are not exposed in fs.constants.】

注意事项:在 Windows 上,只有写权限可以更改,并且没有实现对组、所有者或其他用户权限的区分。

【Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner, or others is not implemented.】

fs.chown(path, uid, gid, callback)#>

异步更改文件的所有者和组。除可能的异常外,不会向完成回调提供任何参数。

【Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX chown(2) 文档。

【See the POSIX chown(2) documentation for more detail.】

fs.close(fd[, callback])#>

关闭文件描述符。除了可能的异常外,完成回调不会提供其他参数。

【Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.】

对任何当前正在通过其他 fs 操作使用的文件描述符 (fd) 调用 fs.close() 可能导致未定义的行为。

【Calling fs.close() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.】

有关更多详细信息,请参阅 POSIX close(2) 文档。

【See the POSIX close(2) documentation for more detail.】

fs.copyFile(src, dest[, mode], callback)#>

异步地将 src 复制到 dest。默认情况下,如果 dest 已存在,则会被覆盖。传递给回调函数的参数除了可能的异常之外,没有其他参数。Node.js 不保证复制操作的原子性。如果在目标文件被打开以进行写入后发生错误,Node.js 将尝试删除目标文件。

【Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.】

mode 是一个可选的整数,用于指定复制操作的行为。可以创建一个由两个或多个值按位 OR 组合而成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)。

  • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,复制操作将失败。
  • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建一个写时复制的反向链接。如果平台不支持写时复制,则将使用备用复制机制。
  • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建一个写时复制的反向链接。如果平台不支持写时复制,则操作将失败。
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)#>

稳定性: 1 - 实验性

  • src <string> | <URL> 要复制的源路径。
  • dest <string> | <URL> 复制到的目标路径。
  • options <Object>
    • dereference <boolean> 取消符号链接引用。默认值: false
    • errorOnExist <boolean>forcefalse 且目标已存在时,抛出错误。默认值: false
    • filter <Function> 用于筛选复制的文件/目录的函数。返回 true 表示复制该项,返回 false 表示忽略。当忽略一个目录时,其所有内容也将被跳过。也可以返回一个解析为 truefalsePromise默认值: undefined
      • src <string> 要复制的源路径。
      • dest <string> 复制到的目标路径。
      • 返回值:<boolean> | <Promise> 一个可以被强制转换为 boolean 的值,或者一个返回该值的 Promise
    • 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>

异步地将整个目录结构从 src 复制到 dest,包括子目录和文件。

【Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.】

将目录复制到另一个目录时,不支持通配符,行为类似于 cp dir1/ dir2/

【When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.】

fs.createReadStream(path[, options])#>

options 可以包含 startend 值,用于读取以下范围内的字节是文件而不是整个文件。startend 都是包容性的, 从0开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围。如果指定 fd,且 start 为 省略或 undefined 时,fs.createReadStream() 会依次读取 当前档案位置。encoding 可以是以下任何一种被接受的 <Buffer>

如果指定了 fdReadStream 将忽略 path 参数,并使用指定的文件描述符。这意味着不会触发 'open' 事件。fd 应该是阻塞的;非阻塞的 fd 应该传递给 <net.Socket>

【If fd is specified, ReadStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to <net.Socket>.】

如果 fd 指向一个只支持阻塞读取的字符设备(例如键盘或声卡),读取操作将不会完成,直到有数据可用。这可能会阻止进程退出以及流自然关闭。

【If fd points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.】

默认情况下,流在被销毁后会触发 'close' 事件。将 emitClose 选项设置为 false 可以更改此行为。

【By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.】

通过提供 fs 选项,可以覆盖 openreadclose 的对应 fs 实现。当提供 fs 选项时,必须提供 read 的覆盖实现。如果未提供 fd,还需要提供 open 的覆盖实现。如果 autoClosetrue,还需要提供 close 的覆盖实现。

【By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option, an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is also required.】

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' 时文件描述符将会自动关闭。

【If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.】

mode 设置文件模式(权限和粘滞位),但仅在文件被创建时生效。

读取 100 个字节长的文件的最后 10 个字节的示例:

【An example to read the last 10 bytes of a file which is 100 bytes long:】

import { createReadStream } from 'node:fs';

createReadStream('sample.txt', { start: 90, end: 99 }); 

如果 options 是字符串,那么它指定了编码。

【If options is a string, then it specifies the encoding.】

fs.createWriteStream(path[, options])#>

options 也可能包含 start 选项,允许在某些地方写入数据 文件开头之后的位置,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围。修改文件而不是 替换它可能需要将 flags 选项设置为 r+,而不是 默认的 Wencoding 可以是<Buffer>接受的任何一种。

如果在 'error''finish' 上将 autoClose 设置为 true(默认行为),文件描述符将会自动关闭。如果 autoClose 为 false,即使发生错误,文件描述符也不会关闭。由应用负责关闭它,并确保不会发生文件描述符泄漏。

【If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.】

默认情况下,流在被销毁后会触发 'close' 事件。将 emitClose 选项设置为 false 可以更改此行为。

【By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.】

通过提供 fs 选项,可以覆盖 openwritewritevclose 对应的 fs 实现。仅覆盖 write() 而不覆盖 writev() 可能会降低性能,因为某些优化(_writev())将被禁用。当提供 fs 选项时,至少需要覆盖 writewritev 其中之一。如果未提供 fd 选项,还需要覆盖 open。如果 autoClosetrue,还需要覆盖 close

【By providing the fs option it is possible to override the corresponding fs implementations for open, write, writev, and close. Overriding write() without writev() can reduce performance as some optimizations (_writev()) will be disabled. When providing the fs option, overrides for at least one of write and writev are required. If no fd option is supplied, an override for open is also required. If autoClose is true, an override for close is also required.】

<fs.ReadStream> 一样,如果指定了 fd<fs.WriteStream> 将会忽略 path 参数,并使用指定的文件描述符。这意味着不会触发 'open' 事件。fd 应该是阻塞的;非阻塞的 fd 应该传给 <net.Socket>

【Like <fs.ReadStream>, if fd is specified, <fs.WriteStream> will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to <net.Socket>.】

如果 options 是字符串,那么它指定了编码。

【If options is a string, then it specifies the encoding.】

fs.exists(path, callback)#>

稳定性: 0 - 已弃用:请改用 fs.stat()fs.access()

通过检查文件系统来测试给定 path 处的元素是否存在。然后使用 true 或 false 调用 callback 参数:

【Test whether or not the element at the given path exists by checking with the file system. Then call the callback argument with either true or false:】

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

【If path is a symbolic link, it is followed. Thus, if path exists but points to a non-existent element, the callback will receive the value false.】

在调用 fs.open()fs.readFile()fs.writeFile() 之前使用 fs.exists() 来检查文件是否存在是不推荐的。这样做会引入竞争条件,因为在两次调用之间,其他进程可能会更改文件的状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不存在时引发的错误。

【Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.】

写 (不推荐)

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;
    });
  }
}); 

上面“不推荐”的示例先检查文件是否存在,然后再使用文件;“推荐”的示例更好,因为它们直接使用文件,并处理可能出现的错误。

【The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.】

一般来说,只有在文件不会被直接使用时才检查文件是否存在,例如当文件的存在是来自另一个进程的信号时。

【In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process.】

fs.fchmod(fd, mode, callback)#>

设置文件的权限。完成回调函数除了可能的异常外,不接受其他参数。

【Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX fchmod(2) 文档。

【See the POSIX fchmod(2) documentation for more detail.】

fs.fchown(fd, uid, gid, callback)#>

设置文件的所有者。除了可能的异常之外,完成回调不会传入任何参数。

【Sets the owner of the file. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX fchown(2) 文档。

【See the POSIX fchown(2) documentation for more detail.】

fs.fdatasync(fd, callback)#>

将与该文件相关的所有当前排队的 I/O 操作强制送入操作系统的同步 I/O 完成状态。有关详细信息,请参阅 POSIX fdatasync(2) 文档。除了可能的异常外,完成回调不传递任何参数。

【Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback.】

fs.fstat(fd[, options], callback)#>

使用文件描述符的 <fs.Stats> 调用回调。

【Invokes the callback with the <fs.Stats> for the file descriptor.】

有关更多详细信息,请参阅 POSIX fstat(2) 文档。

【See the POSIX fstat(2) documentation for more detail.】

fs.fsync(fd, callback)#>

请求将开放的文件描述符的所有数据刷新到存储设备。具体实现取决于操作系统和设备。有关详细信息,请参考 POSIX fsync(2) 文档。除了可能的异常外,不向完成回调提供其他参数。

【Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.】

fs.ftruncate(fd[, len], callback)#>

截断文件描述符。完成回调函数除了可能的异常外,不会传入其他参数。

【Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX ftruncate(2) 文档。

【See the POSIX ftruncate(2) documentation for more detail.】

如果文件描述符指向的文件大于 len 字节,则文件中只会保留前 len 字节。

【If the file referred to by the file descriptor was larger than len bytes, only the first len bytes will be retained in the file.】

例如,下面的程序只保留文件的前四个字节:

【For example, the following program retains only the first four bytes of the file:】

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''):

【If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):】

如果 len 为负数,则将使用 0

【If len is negative then 0 will be used.】

fs.futimes(fd, atime, mtime, callback)#>

更改由提供的文件描述符引用的对象的文件系统时间戳。参见 fs.utimes()

【Change the file system timestamps of the object referenced by the supplied file descriptor. See fs.utimes().】

fs.lchmod(path, mode, callback)#>

稳定性: 0 - 已弃用

更改符号链接的权限。除了可能的异常外,完成回调不会传入其他参数。

【Changes the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback.】

此方法仅在 macOS 上实现。

【This method is only implemented on macOS.】

有关更多详细信息,请参阅 POSIX lchmod(2) 文档。

【See the POSIX lchmod(2) documentation for more detail.】

fs.lchown(path, uid, gid, callback)#>

设置符号链接的所有者。除了可能的异常外,完成回调不会传入其他参数。

【Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX lchown(2) 文档。

【See the POSIX lchown(2) documentation for more detail.】

fs.lutimes(path, atime, mtime, callback)#>

以与 fs.utimes() 相同的方式更改文件的访问和修改时间,区别在于如果路径指向符号链接,则不会解除引用链接:相反,将更改符号链接本身的时间戳。

【Changes the access and modification times of a file in the same way as fs.utimes(), with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.】

完成回调函数不会传入除可能的异常之外的其他参数。

【No arguments other than a possible exception are given to the completion callback.】

fs.link(existingPath, newPath, callback)#>

existingPathnewPath 之间创建一个新的链接。有关更多详细信息,请参阅 POSIX link(2) 文档。完成回调除了可能的异常之外,不会传递其他参数。

【Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.】

fs.lstat(path[, options], callback)#>

获取路径所指向的符号链接的 <fs.Stats>。回调函数接收两个参数 (err, stats),其中 stats 是一个 <fs.Stats> 对象。lstat()stat() 完全相同,只是如果 path 是符号链接,则对链接本身进行 stat,而不是它指向的文件。

【Retrieves the <fs.Stats> for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a <fs.Stats> object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.】

有关更多详细信息,请参阅 POSIX lstat(2) 文档。

【See the POSIX lstat(2) documentation for more details.】

fs.mkdir(path[, options], callback)#>

异步地创建目录。

【Asynchronously creates a directory.】

回调函数会接收一个可能的异常,如果 recursivetrue,还会接收到第一个创建的目录路径 (err[, path])。当 recursivetrue 且没有创建任何目录时(例如,如果目录之前已经存在),path 仍然可能是 undefined

【The callback is given a possible exception and, if recursive is true, the first directory path created, (err[, path]). path can still be undefined when recursive is true, if no directory was created (for instance, if it was previously created).】

可选的 options 参数可以是一个整数,用于指定 mode(权限和粘滞位),或者是一个具有 mode 属性和 recursive 属性的对象,用于指示是否应该创建父目录。当 path 是已存在的目录时调用 fs.mkdir() 只有在 recursive 为 false 时才会导致错误。如果 recursive 为 false 并且目录已存在,则会出现 EEXIST 错误。

【The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false. If recursive is false and the directory exists, an EEXIST error occurs.】

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() 在根目录上也会导致错误:

【On Windows, using fs.mkdir() on the root directory even with recursion will result in an error:】

import { mkdir } from 'node:fs';

mkdir('/', { recursive: true }, (err) => {
  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
}); 

有关更多详细信息,请参阅 POSIX mkdir(2) 文档。

【See the POSIX mkdir(2) documentation for more details.】

fs.mkdtemp(prefix[, options], callback)#>

创建唯一的临时目录。

【Creates a unique temporary directory.】

生成六个随机字符,附加在必需的 prefix 后面以创建唯一的临时目录。由于平台差异,避免在 prefix 中使用尾随的 X 字符。一些平台,特别是 BSD 系统,可能会生成超过六个随机字符,并将 prefix 中尾随的 X 字符替换为随机字符。

【Generates six random characters to be appended behind a required prefix to create a unique temporary directory. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.】

创建的目录路径作为字符串传递给回调函数的第二个参数。

【The created directory path is passed as a string to the callback's second parameter.】

可选的 options 参数可以是指定编码的字符串,或者是一个具有 encoding 属性的对象,用于指定要使用的字符编码。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.】

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)结尾。

【The fs.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within /tmp, the prefix must end with a trailing platform-specific path separator (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)#>

异步文件打开。详情请参阅 POSIX open(2) 文档。

【Asynchronous file open. See the POSIX open(2) documentation for more details.】

mode 设置文件模式(权限和粘滞位),但仅在文件被创建时有效。在 Windows 上,只能修改写权限;参见 fs.chmod()

回调函数接收两个参数 (err, fd)

【The callback gets two arguments (err, fd).】

在 Windows 系统下,一些字符(< > : " / \ | ? *)是保留的,如 命名文件、路径和命名空间 所述。在 NTFS 中,如果文件名包含冒号,Node.js 将会打开文件系统流,如 这个 MSDN 页面 所述。

【Some characters (< > : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.】

基于 fs.open() 的函数也表现出这种行为:fs.writeFile()fs.readFile() 等。

【Functions based on fs.open() exhibit this behavior as well: fs.writeFile(), fs.readFile(), etc.】

fs.openAsBlob(path[, options])#>

稳定性: 1 - 实验性

返回一个其数据由给定文件支持的 <Blob>

【Returns a <Blob> whose data is backed by the given file.】

在创建 <Blob> 之后,文件不得修改。任何修改都会导致读取 <Blob> 数据时出现 DOMException 错误。在创建 Blob 时以及每次读取之前,需要对文件进行同步的状态检查操作,以检测文件数据是否已在磁盘上被修改。

【The file must not be modified after the <Blob> is created. Any modifications will cause reading the <Blob> data to fail with a DOMException error. Synchronous stat operations on the file when the Blob is created, and before each read in order to detect whether the file data has been modified on disk.】

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)#>

异步打开一个目录。有关更多详细信息,请参阅 POSIX 的 opendir(3) 文档。

【Asynchronously open a directory. See the POSIX opendir(3) documentation for more details.】

创建一个 <fs.Dir>,其中包含用于从目录中读取和清理的所有后续功能。

【Creates an <fs.Dir>, which contains all further functions for reading from and cleaning up the directory.】

encoding 选项用于设置在打开目录以及后续读取操作时 path 的编码。

【The encoding option sets the encoding for the path while opening the directory and subsequent read operations.】

fs.read(fd, buffer, offset, length, position, callback)#>

从由 fd 指定的文件中读取数据。

【Read data from the file specified by fd.】

回调函数会接收三个参数,(err, bytesRead, buffer)

【The callback is given the three arguments, (err, bytesRead, buffer).】

如果文件没有被同时修改,当读取的字节数为零时,就到达了文件末尾。

【If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.】

如果以其 util.promisify()ed 版本调用此方法,它会返回一个包含 bytesReadbuffer 属性的 Object 的 Promise。

【If this method is invoked as its util.promisify()ed version, it returns a promise for an Object with bytesRead and buffer properties.】

fs.read() 方法从指定的文件描述符(fd)对应的文件中读取数据。length 参数表示 Node.js 将尝试从内核读取的最大字节数。然而,实际读取的字节数(bytesRead)可能由于各种原因低于指定的 length

【The fs.read() method reads data from the file specified by the file descriptor (fd). The length argument indicates the maximum number of bytes that Node.js will attempt to read from the kernel. However, the actual number of bytes read (bytesRead) can be lower than the specified length for various reasons.】

例如:

【For example:】

  • 如果文件小于指定的 lengthbytesRead 将设置为实际读取的字节数。
  • 如果文件在缓冲区填满之前遇到 EOF(文件结束),Node.js 会读取所有可用的字节直到遇到 EOF,并且回调中的 bytesRead 参数会指示实际读取的字节数,这可能少于指定的 length
  • 如果文件位于慢速网络 filesystem 上或在读取过程中遇到其他问题,bytesRead 可能会小于指定的 length

因此,在使用 fs.read() 时,检查 bytesRead 的值以确定实际从文件中读取了多少字节非常重要。根据你的应用逻辑,你可能需要处理 bytesRead 小于指定 length 的情况,例如,如果你需要读取最少字节,可以将读取调用放在循环中。

【Therefore, when using fs.read(), it's important to check the bytesRead value to determine how many bytes were actually read from the file. Depending on your application logic, you may need to handle cases where bytesRead is lower than the specified length, such as by wrapping the read call in a loop if you require a minimum amount of bytes.】

这种行为类似于 POSIX 的 preadv2 函数。

【This behavior is similar to the POSIX preadv2 function.】

fs.read(fd[, options], callback)#>

fs.read() 函数类似,这个版本接受一个可选的 options 对象。如果未指定 options 对象,它将使用上述默认值。

【Similar to the fs.read() function, this version takes an optional options object. If no options object is specified, it will default with the above values.】

fs.read(fd, buffer[, options], callback)#>

fs.read() 函数类似,这个版本接受一个可选的 options 对象。如果未指定 options 对象,它将使用上述默认值。

【Similar to the fs.read() function, this version takes an optional options object. If no options object is specified, it will default with the above values.】

fs.readdir(path[, options], callback)#>

读取目录的内容。回调函数接收两个参数 (err, files),其中 files 是目录中除 '.''..' 之外的文件名数组。

【Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.】

有关更多详细信息,请参阅 POSIX readdir(3) 文档。

【See the POSIX readdir(3) documentation for more details.】

可选的 options 参数可以是指定编码的字符串,也可以是带有 encoding 属性的对象,用于指定传递给回调函数的文件名使用的字符编码。如果 encoding 设置为 'buffer',返回的文件名将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames passed to the callback. If the encoding is set to 'buffer', the filenames returned will be passed as <Buffer> objects.】

如果将 options.withFileTypes 设置为 true,则 files 数组将包含 <fs.Dirent> 对象。

【If options.withFileTypes is set to true, the files array will contain <fs.Dirent> objects.】

fs.readFile(path[, options], callback)#>

异步地读取文件的全部内容。

【Asynchronously reads the entire contents of a file.】

import { readFile } from 'node:fs';

readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
}); 

回调函数会传入两个参数 (err, data),其中 data 是文件的内容。

【The callback is passed two arguments (err, data), where data is the contents of the file.】

如果未指定编码,则返回原始缓冲区。

【If no encoding is specified, then the raw buffer is returned.】

如果 options 是字符串,则它指定了编码方式:

【If options is a string, then it specifies the encoding:】

import { readFile } from 'node:fs';

readFile('/etc/passwd', 'utf8', callback); 

当路径是一个目录时,fs.readFile()fs.readFileSync() 的行为取决于平台。在 macOS、Linux 和 Windows 上,会返回一个错误。在 FreeBSD 上,会返回目录内容的表示。

【When the path is a directory, the behavior of fs.readFile() and fs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.】

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 调用:

【It is possible to abort an ongoing request using an AbortSignal. If a request is aborted the callback is called with an 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() 进行流式处理。

【The fs.readFile() function buffers the entire file. To minimize memory costs, when possible prefer streaming via fs.createReadStream().】

中止正在进行的请求并不会中止单个操作系统请求,而是中止内部缓冲 fs.readFile 所执行的操作。

【Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.】

文件描述符#>

【File descriptors】

  1. 任何指定的文件描述符都必须支持读取。
  2. 如果将文件描述符指定为 path,它将不会自动关闭。
  3. 读取将从当前位置开始。例如,如果文件中已经有 'Hello World',并且使用文件描述符读取了六个字节,那么使用相同文件描述符调用 fs.readFile() 将返回 'World',而不是 'Hello World'

性能注意事项#>

【Performance Considerations】

fs.readFile() 方法会异步地一次读取文件的一部分内容到内存中,从而允许事件循环在每一块之间切换。这使得读取操作对可能正在使用底层 libuv 线程池的其他活动影响较小,但也意味着将整个文件读取到内存中会花费更长时间。

【The fs.readFile() method asynchronously reads the contents of a file into memory one chunk at a time, allowing the event loop to turn between each chunk. This allows the read operation to have less impact on other activity that may be using the underlying libuv thread pool but means that it will take longer to read a complete file into memory.】

额外的读取开销在不同系统上可能差异很大,并且取决于被读取文件的类型。如果文件类型不是常规文件(例如管道),并且 Node.js 无法确定实际文件大小,每次读取操作将加载 64 KiB 的数据。对于常规文件,每次读取将处理 512 KiB 的数据。

【The additional read overhead can vary broadly on different systems and depends on the type of file being read. If the file type is not a regular file (a pipe for instance) and Node.js is unable to determine an actual file size, each read operation will load on 64 KiB of data. For regular files, each read will process 512 KiB of data.】

对于需要尽可能快速读取文件内容的应用,最好直接使用 fs.read(),并让应用代码自行管理文件内容的完整读取。

【For applications that require as-fast-as-possible reading of file contents, it is better to use fs.read() directly and for application code to manage reading the full contents of the file itself.】

Node.js 的 GitHub 问题 #25741 提供了更多信息以及对不同 Node.js 版本中 fs.readFile() 在多种文件大小下性能的详细分析。

【The Node.js GitHub issue #25741 provides more information and a detailed analysis on the performance of fs.readFile() for multiple file sizes in different Node.js versions.】

fs.readlink(path[, options], callback)#>

读取 path 所引用的符号链接的内容。回调函数会接收两个参数 (err, linkString)

【Reads the contents of the symbolic link referred to by path. The callback gets two arguments (err, linkString).】

有关更多详细信息,请参阅 POSIX readlink(2) 文档。

【See the POSIX readlink(2) documentation for more details.】

可选的 options 参数可以是一个指定编码的字符串,或者是一个具有 encoding 属性的对象,用于指定传递给回调函数的链接路径的字符编码。如果 encoding 设置为 'buffer',则返回的链接路径将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path passed to the callback. If the encoding is set to 'buffer', the link path returned will be passed as a <Buffer> object.】

fs.readv(fd, buffers[, position], callback)#>

从由 fd 指定的文件读取数据,并使用 readv() 写入 ArrayBufferView 数组。

【Read from a file specified by fd and write to an array of ArrayBufferViews using readv().】

position 是指从文件开头开始读取数据的偏移量。如果 typeof position !== 'number',数据将从当前位置开始读取。

回调函数将接收三个参数:errbytesReadbuffersbytesRead 表示从文件中读取的字节数。

【The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.】

如果以其 util.promisify()ed 版本调用此方法,它会返回一个包含 bytesReadbuffers 属性的 Object 的 Promise。

【If this method is invoked as its util.promisify()ed version, it returns a promise for an Object with bytesRead and buffers properties.】

fs.realpath(path[, options], callback)#>

通过解析 ... 和符号链接,异步计算规范路径名。

【Asynchronously computes the canonical pathname by resolving ., .., and symbolic links.】

规范路径名不一定是唯一的。硬链接和绑定挂载可以通过多种路径名访问文件系统实体。

【A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.】

该函数的行为类似于 realpath(3),但有一些例外:

【This function behaves like realpath(3), with some exceptions:】

  1. 在不区分大小写的文件系统上不会进行大小写转换。
  2. 符号链接的最大数量与平台无关,通常比本地 realpath(3) 实现支持的要高得多。

callback 接收两个参数 (err, resolvedPath)。可以使用 process.cwd 来解析相对路径。

【The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths.】

仅支持可以转换为 UTF8 字符串的路径。

【Only paths that can be converted to UTF8 strings are supported.】

可选的 options 参数可以是一个指定编码的字符串,或者是一个包含 encoding 属性的对象,该属性指定要用于传递给回调函数的路径的字符编码。如果 encoding 设置为 'buffer',返回的路径将作为一个 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a <Buffer> object.】

如果 path 解析为套接字或管道,该函数将返回该对象的系统相关名称。

【If path resolves to a socket or a pipe, the function will return a system dependent name for that object.】

不存在的路径会导致 ENOENT 错误。 error.path 是绝对文件路径。

【A path that does not exist results in an ENOENT error. error.path is the absolute file path.】

fs.realpath.native(path[, options], callback)#>

异步实路径(3)。

【Asynchronous realpath(3).】

callback 接受两个参数 (err, resolvedPath)

【The callback gets two arguments (err, resolvedPath).】

仅支持可以转换为 UTF8 字符串的路径。

【Only paths that can be converted to UTF8 strings are supported.】

可选的 options 参数可以是一个指定编码的字符串,或者是一个包含 encoding 属性的对象,该属性指定要用于传递给回调函数的路径的字符编码。如果 encoding 设置为 'buffer',返回的路径将作为一个 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a <Buffer> object.】

在 Linux 上,当 Node.js 与 musl libc 链接时,必须将 procfs 文件系统挂载在 /proc 上,这样该函数才能工作。Glibc 没有这个限制。

【On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.】

fs.rename(oldPath, newPath, callback)#>

异步将位于 oldPath 的文件重命名为提供的 newPath 路径。如果 newPath 已存在,它将被覆盖。如果 newPath 是一个目录,则会引发错误。完成回调中除了可能的异常,不会提供其他参数。

【Asynchronously rename file at oldPath to the pathname provided as newPath. In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.】

另请参见:rename(2)。

【See also: 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>
    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 会以线性回退的方式重试操作,每次重试等待时间比上次增加 retryDelay 毫秒。此选项表示重试次数。如果 recursive 选项不是 true,此选项将被忽略。默认值: 0
    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作在失败时会重试。默认值: false已弃用。
    • retryDelay <integer> 重试之间等待的时间,以毫秒为单位。如果 recursive 选项不为 true,则此选项将被忽略。默认值: 100
  • callback <Function>

异步 rmdir(2)。除了可能的异常外,没有其他参数会传递给完成回调。

【Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.】

在文件(而不是目录)上使用 fs.rmdir() 会在 Windows 上导致 ENOENT 错误,在 POSIX 系统上导致 ENOTDIR 错误。

【Using fs.rmdir() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.】

要获得类似于 rm -rf Unix 命令的行为,请使用 fs.rm(),并设置选项 { recursive: true, force: true }

【To get a behavior similar to the rm -rf Unix command, use fs.rm() with options { recursive: true, force: true }.】

fs.rm(path[, options], callback)#>

  • path <string> | <Buffer> | <URL>
  • options <Object>
    • force <boolean> 当为 true 时,如果 path 不存在,将忽略异常。默认值: false
    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 将以线性回退方式重试操作,每次重试等待时间比上次增加 retryDelay 毫秒。此选项表示重试次数。如果 recursive 选项不是 true,此选项将被忽略。默认值: 0
    • recursive <boolean> 如果为 true,则执行递归删除。在递归模式下,操作失败时会重试。默认值: false
    • retryDelay <integer> 重试之间等待的时间,以毫秒为单位。如果 recursive 选项不为 true,则此选项将被忽略。默认值: 100
  • callback <Function>

异步删除文件和目录(以标准 POSIX rm 工具为模型)。除了可能的异常外,完成回调函数不接受其他参数。

【Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.】

fs.stat(path[, options], callback)#>

异步 stat(2)。回调函数接受两个参数 (err, stats),其中 stats 是一个 <fs.Stats> 对象。

【Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is an <fs.Stats> object.】

如果发生错误,err.code 将是 常见系统错误 中的一个。

【In case of an error, the err.code will be one of Common System Errors.】

fs.stat() 会跟随符号链接。使用 fs.lstat() 来查看链接本身。

在调用 fs.open()fs.readFile()fs.writeFile() 之前使用 fs.stat() 来检查文件是否存在是不推荐的。相反,用户代码应直接打开/读取/写入文件,并处理文件不可用时引发的错误。

【Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.】

如果只想检查文件是否存在而不进行后续操作,建议使用 fs.access()

【To check if a file exists without manipulating it afterwards, fs.access() is recommended.】

例如,给定以下目录结构:

【For example, given the following directory structure:】

- txtDir
-- file.txt
- app.js 

下一个程序将检查给定路径的统计信息:

【The next program will check for the stats of the given paths:】

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);
  });
} 

结果输出将类似于:

【The resulting output will resemble:】

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)#>

异步 statfs(2)。返回包含 path 的已挂载文件系统的信息。回调函数接收两个参数 (err, stats),其中 stats 是一个 <fs.StatFs> 对象。

【Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an <fs.StatFs> object.】

如果发生错误,err.code 将是 常见系统错误 中的一个。

【In case of an error, the err.code will be one of Common System Errors.】

fs.symlink(target, path[, type], callback)#>

创建名为 path 的链接,指向 target。除了可能的异常之外,不会向完成回调提供其他参数。

【Creates the link called path pointing to target. No arguments other than a possible exception are given to the completion callback.】

有关更多详细信息,请参阅 POSIX symlink(2) 文档。

【See the POSIX symlink(2) documentation for more details.】

type 参数仅在 Windows 上可用,在其他平台上会被忽略。它可以设置为 'dir''file''junction'。如果 type 参数不是字符串,Node.js 会自动检测 target 类型并使用 'file''dir'。如果 target 不存在,将使用 'file'。Windows 的连接点(junction points)要求目标路径为绝对路径。使用 'junction' 时,target 参数会自动规范化为绝对路径。NTFS 卷上的连接点只能指向目录。

【The type argument is only available on Windows and ignored on other platforms. It can be set to 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', the target argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.】

相对目标是相对于链接的父目录。

【Relative targets are relative to the link's parent directory.】

import { symlink } from 'node:fs';

symlink('./mew', './mewtwo', callback); 

上面的例子创建了一个符号链接 mewtwo,它指向同一目录下的 mew

【The above example creates a symbolic link mewtwo which points to mew in the same directory:】

$ tree .
.
├── mew
└── mewtwo -> ./mew 

fs.truncate(path[, len], callback)#>

截断文件。除了可能的异常外,没有其他参数会传递给完成回调函数。第一个参数也可以传入文件描述符。在这种情况下,会调用 fs.ftruncate()

【Truncates the file. No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, fs.ftruncate() is called.】

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');
});

传递文件描述符已被弃用,将来可能会导致抛出错误。

【Passing a file descriptor is deprecated and may result in an error being thrown in the future.】

有关更多详细信息,请参阅 POSIX truncate(2) 文档。

【See the POSIX truncate(2) documentation for more details.】

fs.unlink(path, callback)#>

异步删除文件或符号链接。完成回调函数不会接收任何参数,除了可能的异常。

【Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.】

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) 文档。

【See the POSIX unlink(2) documentation for more details.】

fs.unwatchFile(filename[, listener])#>

停止监视 filename 的更改。如果指定了 listener,则只会移除该特定监听器。否则,将移除所有监听器,从而有效地停止对 filename 的监视。

【Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of filename.】

对未被监听的文件名调用 fs.unwatchFile() 不会有任何操作,也不会报错。

【Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.】

使用 fs.watch()fs.watchFile()fs.unwatchFile() 更高效。在可能的情况下,应使用 fs.watch() 替代 fs.watchFile()fs.unwatchFile()

【Using fs.watch() is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.】

fs.utimes(path, atime, mtime, callback)#>

更改由 path 引用的对象的文件系统时间戳。

【Change the file system timestamps of the object referenced by path.】

atimemtime 参数遵循以下规则:

【The atime and mtime arguments follow these rules:】

  • 值可以是表示 Unix 纪元时间(以秒为单位)的数字、Date 对象,或者像 '123456789.0' 这样的数字字符串。
  • 如果该值无法转换为数字,或者是 NaNInfinity-Infinity,将会抛出一个 Error

fs.watch(filename[, options][, listener])#>

监视 filename 的更改,其中 filename 可以是文件或目录。

【Watch for changes on filename, where filename is either a file or a directory.】

第二个参数是可选的。如果将 options 提供为字符串,它指定 encoding。否则,options 应作为对象传递。

【The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.】

监听器回调函数接收两个参数 (eventType, filename)eventType 可以是 'rename''change',而 filename 是触发该事件的文件名。

【The listener callback gets two arguments (eventType, filename). eventType is either 'rename' or 'change', and filename is the name of the file which triggered the event.】

在大多数平台上,每当目录中出现或消失一个文件名时,都会触发 'rename'

【On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.】

监听器回调附加到由 <fs.FSWatcher> 触发的 'change' 事件,但这与 eventType'change' 值并不相同。

【The listener callback is attached to the 'change' event fired by <fs.FSWatcher>, but it is not the same thing as the 'change' value of eventType.】

如果传入 signal,中止相应的 AbortController 将关闭返回的 <fs.FSWatcher>

【If a signal is passed, aborting the corresponding AbortController will close the returned <fs.FSWatcher>.】

注意事项#>

【Caveats】

fs.watch API 在各个平台上的表现并不完全一致,并且在某些情况下无法使用。

【The fs.watch API is not 100% consistent across platforms, and is unavailable in some situations.】

在 Windows 上,如果被监视的目录被移动或重命名,将不会触发任何事件。删除被监视的目录时,会报告 EPERM 错误。

【On Windows, no events will be emitted if the watched directory is moved or renamed. An EPERM error is reported when the watched directory is deleted.】

可用性#>

【Availability】

此功能依赖于底层操作系统提供一种方式,以便在文件系统发生更改时收到通知。

【This feature depends on the underlying operating system providing a way to be notified of file system changes.】

  • 在 Linux 系统上,这使用 inotify(7)
  • 在 BSD 系统上,这使用 kqueue(2)
  • 在 macOS 上,这对于文件使用 kqueue(2),对于目录使用 FSEvents
  • 在 SunOS 系统(包括 Solaris 和 SmartOS)上,这使用 event ports
  • 在 Windows 系统上,此功能取决于 ReadDirectoryChangesW
  • 在 AIX 系统上,此功能依赖于 AHAFS,必须启用它。
  • 在 IBM i 系统上,此功能不受支持。

如果由于某种原因底层功能不可用,那么 fs.watch() 将无法工作,并可能抛出异常。例如,在网络文件系统(NFS、SMB 等)上,或在使用虚拟化软件(如 Vagrant 或 Docker)时,监视文件或目录可能不可靠,甚至在某些情况下不可能。

【If the underlying functionality is not available for some reason, then fs.watch() will not be able to function and may throw an exception. For example, watching files or directories can be unreliable, and in some cases impossible, on network file systems (NFS, SMB, etc) or host file systems when using virtualization software such as Vagrant or Docker.】

仍然可以使用 fs.watchFile(),它使用状态轮询,但这种方法更慢且不太可靠。

【It is still possible to use fs.watchFile(), which uses stat polling, but this method is slower and less reliable.】

索引节点#>

【Inodes】

在 Linux 和 macOS 系统上,fs.watch() 会解析路径到一个 索引节点 并监视 inode。如果被监视的路径被删除并重新创建,它会被分配一个新的 inode。监视会针对删除操作触发事件,但会继续监视_原始_ inode。新的 inode 不会触发事件。这是预期的行为。

【On Linux and macOS systems, fs.watch() resolves the path to an inode and watches the inode. If the watched path is deleted and recreated, it is assigned a new inode. The watch will emit an event for the delete but will continue watching the original inode. Events for the new inode will not be emitted. This is expected behavior.】

AIX 文件在文件的整个生命周期内保持相同的 inode。在 AIX 上保存并关闭被监视的文件会导致两个通知(一个用于添加新内容,另一个用于截断)。

【AIX files retain the same inode for the lifetime of a file. Saving and closing a watched file on AIX will result in two notifications (one for adding new content, and one for truncation).】

文件名参数#>

【Filename argument】

在回调中提供 filename 参数仅在 Linux、macOS、Windows 和 AIX 上受支持。即使在受支持的平台上,也不能保证始终提供 filename。因此,不要假设回调中始终会提供 filename 参数,如果它为 null,需要有一些备用逻辑。

【Providing filename argument in the callback is only supported on Linux, macOS, Windows, and AIX. Even on supported platforms, filename is not always guaranteed to be provided. Therefore, don't assume that filename argument is always provided in the callback, and have some fallback logic if it is 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 的更改。每次访问该文件时,回调 listener 都会被调用。

【Watch for changes on filename. The callback listener will be called each time the file is accessed.】

options 参数可以省略。如果提供,它应该是一个对象。options 对象可以包含一个名为 persistent 的布尔值,用于表示只要有文件被监视,进程是否应继续运行。options 对象可以指定一个 interval 属性,用于表示目标应以毫秒为单位的轮询频率。

【The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.】

listener 接受两个参数:当前的 stat 对象和之前的 stat 对象:

【The listener gets two arguments the current stat object and the previous stat object:】

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 形式表示。

【These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.】

要在文件被修改时收到通知,而不仅仅是被访问,需要比较 curr.mtimeMsprev.mtimeMs

【To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.】

fs.watchFile 操作导致 ENOENT 错误时,它会调用监听器一次,所有字段都为零(或者,对于日期来说,使用 Unix 纪元时间)。如果文件后来被创建,监听器将再次被调用,并提供最新的 stat 对象。这是自 v0.10 以来功能上的变化。

【When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.】

使用 fs.watch()fs.watchFilefs.unwatchFile 更高效。在可能的情况下,应使用 fs.watch 替代 fs.watchFilefs.unwatchFile

【Using fs.watch() is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.】

fs.watchFile() 监视的文件消失又重新出现时,第二次回调事件(文件重新出现)中 previous 的内容将与第一次回调事件(文件消失)中 previous 的内容相同。

【When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).】

这发生在:

【This happens when:】

  • 文件已被删除,随后恢复
  • 文件被重命名,然后再次重命名回原来的名字

fs.write(fd, buffer, offset[, length[, position]], callback)#>

buffer 写入由 fd 指定的文件。

【Write buffer to the file specified by fd.】

offset 决定要写入缓冲区的部分,而 length 是指定要写入字节数的整数。

position 指的是应将此数据写入文件起始位置的偏移量。如果 typeof position !== 'number',数据将写入当前位置。参见 pwrite(2)

回调函数将接收三个参数 (err, bytesWritten, buffer),其中 bytesWritten 指定了从 buffer 写入了多少字节。

【The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.】

如果以其 util.promisify()ed 版本调用此方法,它会返回一个包含 bytesWrittenbuffer 属性的 Object 的 Promise。

【If this method is invoked as its util.promisify()ed version, it returns a promise for an Object with bytesWritten and buffer properties.】

在同一个文件上多次使用 fs.write() 而不等待回调是不安全的。对于这种情况,建议使用 fs.createWriteStream()

【It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream() is recommended.】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

fs.write(fd, buffer[, options], callback)#>

buffer 写入由 fd 指定的文件。

【Write buffer to the file specified by fd.】

与上述 fs.write 函数类似,这个版本接受一个可选的 options 对象。如果未指定 options 对象,将使用上述默认值。

【Similar to the above fs.write function, this version takes an optional options object. If no options object is specified, it will default with the above values.】

fs.write(fd, string[, position[, encoding]], callback)#>

string 写入由 fd 指定的文件。如果 string 不是字符串,将抛出异常。

【Write string to the file specified by fd. If string is not a string, an exception is thrown.】

position 指的是应将此数据写入文件起始位置的偏移量。如果 typeof position !== 'number',数据将写入当前位置。参见 pwrite(2)

encoding 是预期的字符串编码。

回调函数将接收参数 (err, written, string),其中 written 指定传入字符串所需写入的 字节 数。写入的字节数不一定与写入的字符串字符数相同。参见 Buffer.byteLength

【The callback will receive the arguments (err, written, string) where written specifies how many bytes the passed string required to be written. Bytes written is not necessarily the same as string characters written. See Buffer.byteLength.】

在同一个文件上多次使用 fs.write() 而不等待回调是不安全的。对于这种情况,建议使用 fs.createWriteStream()

【It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream() is recommended.】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

在 Windows 上,如果文件描述符连接到控制台(例如 fd == 1stdout),默认情况下包含非 ASCII 字符的字符串将无法正确显示,无论使用何种编码。可以通过使用 chcp 65001 命令更改活动代码页来配置控制台以正确显示 UTF-8。有关更多详细信息,请参阅 chcp 文档。

【On Windows, if the file descriptor is connected to the console (e.g. fd == 1 or stdout) a string containing non-ASCII characters will not be rendered properly by default, regardless of the encoding used. It is possible to configure the console to render UTF-8 properly by changing the active codepage with the chcp 65001 command. See the chcp docs for more details.】

fs.writeFile(file, data[, options], callback)#>

file 是文件名时,会异步将数据写入该文件,如果文件已存在则会替换它。data 可以是字符串或缓冲区。

【When file is a filename, asynchronously writes data to the file, replacing the file if it already exists. data can be a string or a buffer.】

file 是一个文件描述符时,其行为类似于直接调用 fs.write()(这是推荐的做法)。有关使用文件描述符的说明,请参见下面的备注。

【When file is a file descriptor, the behavior is similar to calling fs.write() directly (which is recommended). See the notes below on using a file descriptor.】

如果 data 是缓冲区,则会忽略 encoding 选项。

【The encoding option is ignored if data is a buffer.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

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 是字符串,则它指定了编码方式:

【If options is a string, then it specifies the encoding:】

import { writeFile } from 'node:fs';

writeFile('message.txt', 'Hello Node.js', 'utf8', callback); 

在未等待回调的情况下多次使用 fs.writeFile() 写入同一个文件是不安全的。对于这种情况,推荐使用 fs.createWriteStream()

【It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream() is recommended.】

fs.readFile 类似,fs.writeFile 是一个便捷方法,它在内部执行多次 write 调用以写入传入的缓冲区。对于对性能敏感的代码,建议考虑使用 fs.createWriteStream()

【Similarly to fs.readFile - fs.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using fs.createWriteStream().】

可以使用 <AbortSignal> 来取消 fs.writeFile()。取消是“尽力而为”的,因此仍有可能写入部分数据。

【It is possible to use an <AbortSignal> to cancel an fs.writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.】

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 执行的内部缓冲操作。

【Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs.】

使用 fs.writeFile() 与文件描述符#>

【Using fs.writeFile() with file descriptors】

file 是一个文件描述符时,其行为几乎与直接调用 fs.write() 相同,如下所示:

【When file is a file descriptor, the behavior is almost identical to directly calling fs.write() like:】

import { write } from 'node:fs';
import { Buffer } from 'node:buffer';

write(fd, Buffer.from(data, options.encoding), callback); 

与直接调用 fs.write() 的区别在于,在某些异常情况下,fs.write() 可能只写入缓冲区的一部分,需要重试才能写入剩余的数据,而 fs.writeFile() 会重试直到数据完全写入(或发生错误)。

【The difference from directly calling fs.write() is that under some unusual conditions, fs.write() might write only part of the buffer and need to be retried to write the remaining data, whereas fs.writeFile() retries until the data is entirely written (or an error occurs).】

这所带来的影响常常是混淆的来源。在文件描述符的情况下,文件并没有被替换!数据不一定会写入文件的开头,文件的原始数据可能在新写入的数据之前和/或之后保留。

【The implications of this are a common source of confusion. In the file descriptor case, the file is not replaced! The data is not necessarily written to the beginning of the file, and the file's original data may remain before and/or after the newly written data.】

例如,如果 fs.writeFile() 连续调用两次,第一次写入字符串 'Hello',然后写入字符串 ', World',文件将包含 'Hello, World',并且可能包含一些文件原有的数据(取决于原始文件的大小以及文件描述符的位置)。如果使用文件名而不是描述符,文件将保证只包含 ', World'

【For example, if fs.writeFile() is called twice in a row, first to write the string 'Hello', then to write the string ', World', the file would contain 'Hello, World', and might contain some of the file's original data (depending on the size of the original file, and the position of the file descriptor). If a file name had been used instead of a descriptor, the file would be guaranteed to contain only ', World'.】

fs.writev(fd, buffers[, position], callback)#>

使用 writev() 将一个 ArrayBufferView 数组写入由 fd 指定的文件。

【Write an array of ArrayBufferViews to the file specified by fd using writev().】

position 是指从文件开头开始写入此数据的偏移量。如果 typeof position !== 'number',数据将会写入当前位置。

回调函数将接受三个参数:errbytesWrittenbuffersbytesWritten 表示从 buffers 中写入了多少字节。

【The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.】

如果此方法被 util.promisify() 处理,它将返回一个包含 bytesWrittenbuffers 属性的 Object 的 Promise。

【If this method is util.promisify()ed, it returns a promise for an Object with bytesWritten and buffers properties.】

在同一个文件上多次使用 fs.writev() 而不等待回调是不安全的。在这种情况下,请使用 fs.createWriteStream()

【It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream().】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

同步 API#>

【Synchronous API】

同步 API 以同步方式执行所有操作,在操作完成或失败之前会阻塞事件循环。

【The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails.】

fs.accessSync(path[, mode])#>

同步测试用户对指定 path 的文件或目录的权限。mode 参数是一个可选的整数,用于指定要执行的可访问性检查。mode 应该是值 fs.constants.F_OK,或者是由 fs.constants.R_OKfs.constants.W_OKfs.constants.X_OK 通过按位或组成的掩码(例如 fs.constants.W_OK | fs.constants.R_OK)。检查 文件访问常量 以获取 mode 的可能值。

【Synchronously tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g. fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.】

如果任何辅助功能检查失败,将抛出 Error。否则,该方法将返回 undefined

【If any of the accessibility checks fail, an Error will be thrown. Otherwise, the method will return 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])#>

同步将数据追加到文件中,如果文件尚不存在则创建该文件。data 可以是字符串或 <Buffer>

【Synchronously append data to a file, creating the file if it does not yet exist. data can be a string or a <Buffer>.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

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 是字符串,则它指定了编码方式:

【If options is a string, then it specifies the encoding:】

import { appendFileSync } from 'node:fs';

appendFileSync('message.txt', 'data to append', 'utf8'); 

path 可以指定为已打开以便追加的数字文件描述符(使用 fs.open()fs.openSync())。该文件描述符不会自动关闭。

【The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.】

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.chmodSync(path, mode)#>

有关详细信息,请参阅此 API 异步版本的文档:fs.chmod()

【For detailed information, see the documentation of the asynchronous version of this API: fs.chmod().】

有关更多详细信息,请参阅 POSIX chmod(2) 文档。

【See the POSIX chmod(2) documentation for more detail.】

fs.chownSync(path, uid, gid)#>

同步更改文件的所有者和组。返回 undefined。 这是 fs.chown() 的同步版本。

【Synchronously changes owner and group of a file. Returns undefined. This is the synchronous version of fs.chown().】

有关更多详细信息,请参阅 POSIX chown(2) 文档。

【See the POSIX chown(2) documentation for more detail.】

fs.closeSync(fd)#>

关闭文件描述符。返回 undefined

【Closes the file descriptor. Returns undefined.】

在通过任何其他 fs 操作使用中的任何文件描述符 (fd) 上调用 fs.closeSync() 可能会导致未定义的行为。

【Calling fs.closeSync() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.】

有关更多详细信息,请参阅 POSIX close(2) 文档。

【See the POSIX close(2) documentation for more detail.】

fs.copyFileSync(src, dest[, mode])#>

同步将 src 复制到 dest。默认情况下,如果 dest 已经存在,会被覆盖。返回 undefined。Node.js 不保证复制操作的原子性。如果在目标文件已打开用于写入后发生错误,Node.js 会尝试删除目标文件。

【Synchronously copies src to dest. By default, dest is overwritten if it already exists. Returns undefined. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.】

mode 是一个可选的整数,用于指定复制操作的行为。可以创建一个由两个或多个值按位 OR 组合而成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)。

  • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,复制操作将失败。
  • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建一个写时复制的反向链接。如果平台不支持写时复制,则将使用备用复制机制。
  • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建一个写时复制的反向链接。如果平台不支持写时复制,则操作将失败。
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])#>

稳定性: 1 - 实验性

  • src <string> | <URL> 要复制的源路径。
  • dest <string> | <URL> 复制到的目标路径。
  • options <Object>
    • dereference <boolean> 取消符号链接引用。默认值: false
    • errorOnExist <boolean>forcefalse 且目标已存在时,抛出错误。默认值: false
    • filter <Function> 用于筛选复制的文件/目录的函数。返回 true 表示复制该项目,返回 false 则忽略它。忽略目录时,其所有内容也将被跳过。默认值: undefined
      • src <string> 要复制的源路径。
      • dest <string> 复制到的目标路径。
      • 返回值:<boolean> 任何可以强制转换为 boolean 的非 Promise 值。
    • 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,包括子目录和文件。

【Synchronously copies the entire directory structure from src to dest, including subdirectories and files.】

将目录复制到另一个目录时,不支持通配符,行为类似于 cp dir1/ dir2/

【When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.】

fs.existsSync(path)#>

如果路径存在,则返回 true,否则返回 false

【Returns true if the path exists, false otherwise.】

有关详细信息,请参阅此 API 异步版本的文档:fs.exists()

【For detailed information, see the documentation of the asynchronous version of this 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.fchmodSync(fd, mode)#>

设置文件的权限。返回 undefined

【Sets the permissions on the file. Returns undefined.】

有关更多详细信息,请参阅 POSIX fchmod(2) 文档。

【See the POSIX fchmod(2) documentation for more detail.】

fs.fchownSync(fd, uid, gid)#>

设置文件的所有者。返回 undefined

【Sets the owner of the file. Returns undefined.】

有关更多详细信息,请参阅 POSIX fchown(2) 文档。

【See the POSIX fchown(2) documentation for more detail.】

fs.fdatasyncSync(fd)#>

将与文件关联的所有当前排队的 I/O 操作强制进入操作系统的同步 I/O 完成状态。有关详细信息,请参阅 POSIX fdatasync(2) 文档。返回 undefined

【Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns undefined.】

fs.fstatSync(fd[, options])#>

获取文件描述符的 <fs.Stats>

【Retrieves the <fs.Stats> for the file descriptor.】

有关更多详细信息,请参阅 POSIX fstat(2) 文档。

【See the POSIX fstat(2) documentation for more detail.】

fs.fsyncSync(fd)#>

请求将打开文件描述符的所有数据刷新到存储设备。具体实现取决于操作系统和设备。有关更多详细信息,请参考 POSIX fsync(2) 文档。返回值为 undefined

【Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns undefined.】

fs.ftruncateSync(fd[, len])#>

截断文件描述符。返回 undefined

【Truncates the file descriptor. Returns undefined.】

有关详细信息,请参阅此 API 异步版本的文档:fs.ftruncate()

【For detailed information, see the documentation of the asynchronous version of this API: fs.ftruncate().】

fs.futimesSync(fd, atime, mtime)#>

fs.futimes() 的同步版本。返回 undefined

【Synchronous version of fs.futimes(). Returns undefined.】

fs.lchmodSync(path, mode)#>

稳定性: 0 - 已弃用

更改符号链接的权限。返回 undefined

【Changes the permissions on a symbolic link. Returns undefined.】

此方法仅在 macOS 上实现。

【This method is only implemented on macOS.】

有关更多详细信息,请参阅 POSIX lchmod(2) 文档。

【See the POSIX lchmod(2) documentation for more detail.】

fs.lchownSync(path, uid, gid)#>

为路径设置所有者。返回 undefined

【Set the owner for the path. Returns undefined.】

有关更多详细信息,请参阅 POSIX lchown(2) 文档。

【See the POSIX lchown(2) documentation for more details.】

fs.lutimesSync(path, atime, mtime)#>

更改由 path 引用的符号链接的文件系统时间戳。当参数不正确或操作失败时,返回 undefined 或抛出异常。这是 fs.lutimes() 的同步版本。

【Change the file system timestamps of the symbolic link referenced by path. Returns undefined, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of fs.lutimes().】

fs.linkSync(existingPath, newPath)#>

existingPath 创建到 newPath 的新链接。详细信息请参阅 POSIX link(2) 文档。返回 undefined

【Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. Returns undefined.】

fs.lstatSync(path[, options])#>

获取由 path 指向的符号链接的 <fs.Stats>

【Retrieves the <fs.Stats> for the symbolic link referred to by path.】

有关更多详细信息,请参阅 POSIX lstat(2) 文档。

【See the POSIX lstat(2) documentation for more details.】

fs.mkdirSync(path[, options])#>

同步创建一个目录。返回 undefined,或者如果 recursivetrue,则返回创建的第一个目录路径。这是 fs.mkdir() 的同步版本。

【Synchronously creates a directory. Returns undefined, or if recursive is true, the first directory path created. This is the synchronous version of fs.mkdir().】

有关更多详细信息,请参阅 POSIX mkdir(2) 文档。

【See the POSIX mkdir(2) documentation for more details.】

fs.mkdtempSync(prefix[, options])#>

返回创建的目录路径。

【Returns the created directory path.】

有关详细信息,请参阅此 API 异步版本的文档:fs.mkdtemp()

【For detailed information, see the documentation of the asynchronous version of this API: fs.mkdtemp().】

可选的 options 参数可以是指定编码的字符串,或者是一个具有 encoding 属性的对象,用于指定要使用的字符编码。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.】

fs.opendirSync(path[, options])#>

同步打开一个目录。参见 opendir(3)

【Synchronously open a directory. See opendir(3).】

创建一个 <fs.Dir>,其中包含用于从目录中读取和清理的所有后续功能。

【Creates an <fs.Dir>, which contains all further functions for reading from and cleaning up the directory.】

encoding 选项用于设置在打开目录以及后续读取操作时 path 的编码。

【The encoding option sets the encoding for the path while opening the directory and subsequent read operations.】

fs.openSync(path[, flags[, mode]])#>

返回表示文件描述符的整数。

【Returns an integer representing the file descriptor.】

有关详细信息,请参阅此 API 异步版本的文档:fs.open()

【For detailed information, see the documentation of the asynchronous version of this API: fs.open().】

fs.readdirSync(path[, options])#>

读取目录的内容。

【Reads the contents of the directory.】

有关更多详细信息,请参阅 POSIX readdir(3) 文档。

【See the POSIX readdir(3) documentation for more details.】

可选的 options 参数可以是指定编码的字符串,或者是包含 encoding 属性的对象,用于指定返回的文件名所使用的字符编码。如果 encoding 设置为 'buffer',返回的文件名将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as <Buffer> objects.】

如果 options.withFileTypes 设置为 true,结果将包含 <fs.Dirent> 对象。

【If options.withFileTypes is set to true, the result will contain <fs.Dirent> objects.】

fs.readFileSync(path[, options])#>

返回 path 的内容。

【Returns the contents of the path.】

有关详细信息,请参阅此 API 异步版本的文档:fs.readFile()

【For detailed information, see the documentation of the asynchronous version of this API: fs.readFile().】

如果指定了 encoding 选项,则该函数返回一个字符串。否则,它返回一个缓冲区。

【If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.】

类似于 fs.readFile(),当路径是目录时,fs.readFileSync() 的行为取决于平台。

【Similar to fs.readFile(), when the path is a directory, the behavior of fs.readFileSync() is platform-specific.】

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])#>

返回符号链接的字符串值。

【Returns the symbolic link's string value.】

有关更多详细信息,请参阅 POSIX readlink(2) 文档。

【See the POSIX readlink(2) documentation for more details.】

可选的 options 参数可以是指定编码的字符串,也可以是带有 encoding 属性的对象,用于指定返回的链接路径使用的字符编码。如果 encoding 设置为 'buffer',返回的链接路径将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a <Buffer> object.】

fs.readSync(fd, buffer, offset, length[, position])#>

返回 bytesRead 的数量。

【Returns the number of bytesRead.】

有关详细信息,请参阅此 API 异步版本的文档:fs.read()

【For detailed information, see the documentation of the asynchronous version of this API: fs.read().】

fs.readSync(fd, buffer[, options])#>

返回 bytesRead 的数量。

【Returns the number of bytesRead.】

与上述 fs.readSync 函数类似,这个版本接受一个可选的 options 对象。如果未指定 options 对象,将使用上述默认值。

【Similar to the above fs.readSync function, this version takes an optional options object. If no options object is specified, it will default with the above values.】

有关详细信息,请参阅此 API 异步版本的文档:fs.read()

【For detailed information, see the documentation of the asynchronous version of this API: fs.read().】

fs.readvSync(fd, buffers[, position])#>

有关详细信息,请参阅此 API 异步版本的文档:fs.readv()

【For detailed information, see the documentation of the asynchronous version of this API: fs.readv().】

fs.realpathSync(path[, options])#>

返回解析的路径名。

【Returns the resolved pathname.】

有关详细信息,请参阅此 API 异步版本的文档:fs.realpath()

【For detailed information, see the documentation of the asynchronous version of this API: fs.realpath().】

fs.realpathSync.native(path[, options])#>

同步实路径(3)。

【Synchronous realpath(3).】

仅支持可以转换为 UTF8 字符串的路径。

【Only paths that can be converted to UTF8 strings are supported.】

可选的 options 参数可以是指定编码的字符串,或者是具有 encoding 属性的对象,用于指定返回路径使用的字符编码。如果 encoding 设置为 'buffer',则返回的路径将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path returned. If the encoding is set to 'buffer', the path returned will be passed as a <Buffer> object.】

在 Linux 上,当 Node.js 与 musl libc 链接时,必须将 procfs 文件系统挂载在 /proc 上,这样该函数才能工作。Glibc 没有这个限制。

【On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.】

fs.renameSync(oldPath, newPath)#>

将文件从 oldPath 重命名为 newPath。返回 undefined

【Renames the file from oldPath to newPath. Returns undefined.】

有关更多详细信息,请参阅 POSIX rename(2) 文档。

【See the POSIX rename(2) documentation for more details.】

fs.rmdirSync(path[, options])#>

  • path <string> | <Buffer> | <URL>
  • options <Object>
    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 会以线性回退的方式重试操作,每次重试等待时间比上次增加 retryDelay 毫秒。此选项表示重试次数。如果 recursive 选项不是 true,此选项将被忽略。默认值: 0
    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作在失败时会重试。默认值: false已弃用。
    • retryDelay <integer> 重试之间等待的时间,以毫秒为单位。如果 recursive 选项不为 true,则此选项将被忽略。默认值: 100

同步 rmdir(2)。返回 undefined

【Synchronous rmdir(2). Returns undefined.】

在文件(而不是目录)上使用 fs.rmdirSync() 会在 Windows 上导致 ENOENT 错误,在 POSIX 系统上导致 ENOTDIR 错误。

【Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.】

要获得类似于 rm -rf Unix 命令的行为,请使用 fs.rmSync(),并设置选项 { recursive: true, force: true }

【To get a behavior similar to the rm -rf Unix command, use fs.rmSync() with options { recursive: true, force: true }.】

fs.rmSync(path[, options])#>

  • path <string> | <Buffer> | <URL>
  • options <Object>
    • force <boolean> 当为 true 时,如果 path 不存在,将忽略异常。默认值: false
    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 将以线性回退方式重试操作,每次重试等待时间比上次增加 retryDelay 毫秒。此选项表示重试次数。如果 recursive 选项不是 true,此选项将被忽略。默认值: 0
    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作失败时会重试。默认值: false
    • retryDelay <integer> 重试之间等待的时间,以毫秒为单位。如果 recursive 选项不为 true,则此选项将被忽略。默认值: 100

同步删除文件和目录(仿照标准的 POSIX rm 工具)。返回 undefined

【Synchronously removes files and directories (modeled on the standard POSIX rm utility). Returns undefined.】

fs.statSync(path[, options])#>

获取该路径的 <fs.Stats>

【Retrieves the <fs.Stats> for the path.】

fs.statfsSync(path[, options])#>

同步 statfs(2)。返回包含 path 的已挂载文件系统的信息。

【Synchronous statfs(2). Returns information about the mounted file system which contains path.】

如果发生错误,err.code 将是 常见系统错误 中的一个。

【In case of an error, the err.code will be one of Common System Errors.】

fs.symlinkSync(target, path[, type])#>

返回 undefined

【Returns undefined.】

有关详细信息,请参阅此 API 异步版本的文档:fs.symlink()

【For detailed information, see the documentation of the asynchronous version of this API: fs.symlink().】

fs.truncateSync(path[, len])#>

截断文件。返回 undefined。也可以传递文件描述符作为第一个参数。在这种情况下,将调用 fs.ftruncateSync()

【Truncates the file. Returns undefined. A file descriptor can also be passed as the first argument. In this case, fs.ftruncateSync() is called.】

传递文件描述符已被弃用,将来可能会导致抛出错误。

【Passing a file descriptor is deprecated and may result in an error being thrown in the future.】

fs.unlinkSync(path)#>

同步 unlink(2)。返回 undefined

【Synchronous unlink(2). Returns undefined.】

fs.utimesSync(path, atime, mtime)#>

返回 undefined

【Returns undefined.】

有关详细信息,请参阅此 API 异步版本的文档:fs.utimes()

【For detailed information, see the documentation of the asynchronous version of this API: fs.utimes().】

fs.writeFileSync(file, data[, options])#>

返回 undefined

【Returns undefined.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

有关详细信息,请参阅此 API 异步版本的文档:fs.writeFile()

【For detailed information, see the documentation of the asynchronous version of this API: fs.writeFile().】

fs.writeSync(fd, buffer, offset[, length[, position]])#>

有关详细信息,请参阅此 API 异步版本的文档:fs.write(fd, buffer...)

【For detailed information, see the documentation of the asynchronous version of this API: fs.write(fd, buffer...).】

fs.writeSync(fd, buffer[, options])#>

有关详细信息,请参阅此 API 异步版本的文档:fs.write(fd, buffer...)

【For detailed information, see the documentation of the asynchronous version of this API: fs.write(fd, buffer...).】

fs.writeSync(fd, string[, position[, encoding]])#>

有关详细信息,请参阅此 API 异步版本的文档:fs.write(fd, string...)

【For detailed information, see the documentation of the asynchronous version of this API: fs.write(fd, string...).】

fs.writevSync(fd, buffers[, position])#>

有关详细信息,请参阅此 API 异步版本的文档:fs.writev()

【For detailed information, see the documentation of the asynchronous version of this API: fs.writev().】

常见对象#>

【Common Objects】

常见对象在所有文件系统 API 变体(Promise、回调和同步)中都是共享的。

【The common objects are shared by all of the file system API variants (promise, callback, and synchronous).】

类:fs.Dir#>

【Class: fs.Dir

表示目录流的类。

【A class representing a directory stream.】

fs.opendir()fs.opendirSync()fsPromises.opendir() 创建。

【Created by fs.opendir(), fs.opendirSync(), or 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> 对象将在迭代器退出后自动关闭。

【When using the async iterator, the <fs.Dir> object will be automatically closed after the iterator exits.】

dir.close()#>

异步关闭目录的底层资源句柄。随后进行的读取操作将导致错误。

【Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors.】

返回一个承诺,该承诺将在资源关闭后兑现。

【A promise is returned that will be fulfilled after the resource has been closed.】

dir.close(callback)#>

异步关闭目录的底层资源句柄。随后进行的读取操作将导致错误。

【Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors.】

callback 会在资源句柄关闭后被调用。

【The callback will be called after the resource handle has been closed.】

dir.closeSync()#>

同步关闭目录的底层资源句柄。后续的读取操作将导致错误。

【Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors.】

dir.path#>

此目录的只读路径,如提供给 fs.opendir()fs.opendirSync()fsPromises.opendir()

【The read-only path of this directory as was provided to fs.opendir(), fs.opendirSync(), or fsPromises.opendir().】

dir.read()#>

通过 readdir(3) 异步读取下一个目录条目,作为 <fs.Dirent>

【Asynchronously read the next directory entry via readdir(3) as an <fs.Dirent>.】

返回一个承诺,该承诺将在读取到 <fs.Dirent> 时被兑现,如果没有更多目录条目可读,则返回 null

【A promise is returned that will be fulfilled with an <fs.Dirent>, or null if there are no more directory entries to read.】

此函数返回的目录条目没有特定顺序,它们的顺序由操作系统的底层目录机制提供。在迭代目录时添加或删除的条目可能不会包含在迭代结果中。

【Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.】

dir.read(callback)#>

通过 readdir(3) 异步读取下一个目录条目,作为 <fs.Dirent>

【Asynchronously read the next directory entry via readdir(3) as an <fs.Dirent>.】

读取完成后,callback 将被调用,并传入一个 <fs.Dirent>,如果没有更多目录条目可读,则传入 null

【After the read is completed, the callback will be called with an <fs.Dirent>, or null if there are no more directory entries to read.】

此函数返回的目录条目没有特定顺序,它们的顺序由操作系统的底层目录机制提供。在迭代目录时添加或删除的条目可能不会包含在迭代结果中。

【Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.】

dir.readSync()#>

以同步方式将下一个目录项读取为 <fs.Dirent>。更多详情请参见 POSIX readdir(3) 文档。

【Synchronously read the next directory entry as an <fs.Dirent>. See the POSIX readdir(3) documentation for more detail.】

如果没有更多的目录条目可读取,将返回 null

【If there are no more directory entries to read, null will be returned.】

此函数返回的目录条目没有特定顺序,它们的顺序由操作系统的底层目录机制提供。在迭代目录时添加或删除的条目可能不会包含在迭代结果中。

【Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.】

dir[Symbol.asyncIterator]()#>

异步遍历目录,直到所有条目都被读取。有关更多详细信息,请参阅 POSIX readdir(3) 文档。

【Asynchronously iterates over the directory until all entries have been read. Refer to the POSIX readdir(3) documentation for more detail.】

异步迭代器返回的条目始终是 <fs.Dirent>dir.read()null 情况在内部已处理。

【Entries returned by the async iterator are always an <fs.Dirent>. The null case from dir.read() is handled internally.】

请参见 <fs.Dir> 了解示例。

【See <fs.Dir> for an example.】

此迭代器返回的目录条目没有特定顺序,它们是由操作系统的底层目录机制提供的。在迭代目录的过程中添加或删除的条目可能不会包含在迭代结果中。

【Directory entries returned by this iterator are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.】

类:fs.Dirent#>

【Class: fs.Dirent

目录项的表示,可以是目录中的文件或子目录,由从 <fs.Dir> 读取时返回。目录项是文件名和文件类型的组合。

【A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an <fs.Dir>. The directory entry is a combination of the file name and file type pairs.】

此外,当调用 fs.readdir()fs.readdirSync() 并将 withFileTypes 选项设置为 true 时,返回的数组将填充 <fs.Dirent> 对象,而不是字符串或 <Buffer>

【Additionally, when fs.readdir() or fs.readdirSync() is called with the withFileTypes option set to true, the resulting array is filled with <fs.Dirent> objects, rather than strings or <Buffer>s.】

dirent.isBlockDevice()#>

如果 <fs.Dirent> 对象描述的是块设备,则返回 true

【Returns true if the <fs.Dirent> object describes a block device.】

dirent.isCharacterDevice()#>

如果 <fs.Dirent> 对象描述的是字符设备,则返回 true

【Returns true if the <fs.Dirent> object describes a character device.】

dirent.isDirectory()#>

如果 <fs.Dirent> 对象描述的是文件系统目录,则返回 true

【Returns true if the <fs.Dirent> object describes a file system directory.】

dirent.isFIFO()#>

如果 <fs.Dirent> 对象描述的是先进先出(FIFO)管道,则返回 true

【Returns true if the <fs.Dirent> object describes a first-in-first-out (FIFO) pipe.】

dirent.isFile()#>

如果 <fs.Dirent> 对象描述的是普通文件,则返回 true

【Returns true if the <fs.Dirent> object describes a regular file.】

dirent.isSocket()#>

如果 <fs.Dirent> 对象描述的是套接字,则返回 true

【Returns true if the <fs.Dirent> object describes a socket.】

dirent.isSymbolicLink()#>

如果 <fs.Dirent> 对象描述的是符号链接,则返回 true

【Returns true if the <fs.Dirent> object describes a symbolic link.】

dirent.name#>

<fs.Dirent> 对象所指的文件名。该值的类型由传递给 fs.readdir()fs.readdirSync()options.encoding 决定。

【The file name that this <fs.Dirent> object refers to. The type of this value is determined by the options.encoding passed to fs.readdir() or fs.readdirSync().】

dirent.parentPath#>

稳定性: 1 - 实验性

<fs.Dirent> 对象所指向的文件的父目录路径。

【The path to the parent directory of the file this <fs.Dirent> object refers to.】

dirent.path#>

稳定性: 0 - 弃用:请改用 dirent.parentPath

dirent.parentPath 的别名。

【Alias for dirent.parentPath.】

类:fs.FSWatcher#>

【Class: fs.FSWatcher

成功调用 fs.watch() 方法将返回一个新的 <fs.FSWatcher> 对象。

【A successful call to fs.watch() method will return a new <fs.FSWatcher> object.】

每当特定的被监视文件被修改时,所有 <fs.FSWatcher> 对象都会触发 'change' 事件。

【All <fs.FSWatcher> objects emit a 'change' event whenever a specific watched file is modified.】

事件:'change'#>

【Event: 'change'

  • eventType <string> 已发生的更改事件类型
  • filename <string> | <Buffer> 已更改的文件名(如果相关/可用)

当被监视的目录或文件发生变化时触发。详情请参见 fs.watch()

【Emitted when something changes in a watched directory or file. See more details in fs.watch().】

filename 参数可能根据操作系统的支持情况而未提供。如果提供了 filename,当 fs.watch() 调用时其 encoding 选项设置为 'buffer'filename 将作为 <Buffer> 提供,否则 filename 将是一个 UTF-8 字符串。

【The filename argument may not be provided depending on operating system support. If filename is provided, it will be provided as a <Buffer> if fs.watch() is called with its encoding option set to 'buffer', otherwise filename will be a UTF-8 string.】

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'#>

【Event: 'close'

当观察者停止监听变化时触发。关闭的 <fs.FSWatcher> 对象在事件处理程序中不再可用。

【Emitted when the watcher stops watching for changes. The closed <fs.FSWatcher> object is no longer usable in the event handler.】

事件:'错误'#>

【Event: 'error'

当监视文件时发生错误时触发。发生错误的 <fs.FSWatcher> 对象在事件处理程序中不再可用。

【Emitted when an error occurs while watching the file. The errored <fs.FSWatcher> object is no longer usable in the event handler.】

watcher.close()#>

停止监视给定的 <fs.FSWatcher> 的更改。一旦停止,该 <fs.FSWatcher> 对象将不再可用。

【Stop watching for changes on the given <fs.FSWatcher>. Once stopped, the <fs.FSWatcher> object is no longer usable.】

watcher.ref()#>

调用时,请求 Node.js 事件循环在 <fs.FSWatcher> 活跃期间 退出。多次调用 watcher.ref() 不会产生任何效果。

【When called, requests that the Node.js event loop not exit so long as the <fs.FSWatcher> is active. Calling watcher.ref() multiple times will have no effect.】

默认情况下,所有 <fs.FSWatcher> 对象都是“引用”的,因此通常不需要调用 watcher.ref(),除非之前调用过 watcher.unref()

【By default, all <fs.FSWatcher> objects are "ref'ed", making it normally unnecessary to call watcher.ref() unless watcher.unref() had been called previously.】

watcher.unref()#>

当被调用时,活动的 <fs.FSWatcher> 对象不需要 Node.js 事件循环保持活跃。如果没有其他活动使事件循环继续运行,进程可能会在 <fs.FSWatcher> 对象的回调被调用之前退出。多次调用 watcher.unref() 将不会产生任何效果。

【When called, the active <fs.FSWatcher> object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the <fs.FSWatcher> object's callback is invoked. Calling watcher.unref() multiple times will have no effect.】

类:fs.StatWatcher#>

【Class: fs.StatWatcher

成功调用 fs.watchFile() 方法将返回一个新的 <fs.StatWatcher> 对象。

【A successful call to fs.watchFile() method will return a new <fs.StatWatcher> object.】

watcher.ref()#>

被调用时,请求 Node.js 事件循环在 <fs.StatWatcher> 处于活动状态时不退出。多次调用 watcher.ref() 不会有任何效果。

【When called, requests that the Node.js event loop not exit so long as the <fs.StatWatcher> is active. Calling watcher.ref() multiple times will have no effect.】

默认情况下,所有 <fs.StatWatcher> 对象都是“引用”的,通常不需要调用 watcher.ref(),除非之前已经调用过 watcher.unref()

【By default, all <fs.StatWatcher> objects are "ref'ed", making it normally unnecessary to call watcher.ref() unless watcher.unref() had been called previously.】

watcher.unref()#>

当被调用时,活动的 <fs.StatWatcher> 对象不需要 Node.js 事件循环保持活动状态。如果没有其他活动保持事件循环运行,进程可能会在 <fs.StatWatcher> 对象的回调被调用之前退出。多次调用 watcher.unref() 将不会有任何效果。

【When called, the active <fs.StatWatcher> object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the <fs.StatWatcher> object's callback is invoked. Calling watcher.unref() multiple times will have no effect.】

类:fs.ReadStream#>

【Class: fs.ReadStream

使用 fs.createReadStream() 函数创建并返回 <fs.ReadStream> 的实例。

【Instances of <fs.ReadStream> are created and returned using the fs.createReadStream() function.】

事件:'close'#>

【Event: 'close'

<fs.ReadStream> 的底层文件描述符被关闭时触发。

【Emitted when the <fs.ReadStream>'s underlying file descriptor has been closed.】

事件:'open'#>

【Event: 'open'

<fs.ReadStream> 的文件描述符已被打开时触发。

【Emitted when the <fs.ReadStream>'s file descriptor has been opened.】

事件:'ready'#>

【Event: 'ready'

<fs.ReadStream> 可以使用时触发。

【Emitted when the <fs.ReadStream> is ready to be used.】

'open' 之后立即触发。

【Fires immediately after 'open'.】

readStream.bytesRead#>

到目前为止已读取的字节数。

【The number of bytes that have been read so far.】

readStream.path#>

流正在读取的文件路径,如在 fs.createReadStream() 的第一个参数中指定。如果 path 以字符串形式传入,那么 readStream.path 将是一个字符串。如果 path<Buffer> 形式传入,那么 readStream.path 将是 <Buffer>。如果指定了 fd,则 readStream.path 将是 undefined

【The path to the file the stream is reading from as specified in the first argument to fs.createReadStream(). If path is passed as a string, then readStream.path will be a string. If path is passed as a <Buffer>, then readStream.path will be a <Buffer>. If fd is specified, then readStream.path will be undefined.】

readStream.pending#>

如果底层文件尚未打开,即在触发 'ready' 事件之前,该属性为 true

【This property is true if the underlying file has not been opened yet, i.e. before the 'ready' event is emitted.】

类:fs.Stats#>

【Class: fs.Stats

<fs.Stats> 对象提供有关文件的信息。

【A <fs.Stats> object provides information about a file.】

fs.stat()fs.lstat()fs.fstat() 及其同步对应方法返回的对象都是此类型。如果传递给这些方法的 options 中的 bigint 为 true,则数值将为 bigint 而不是 number,并且对象将包含附加的以 Ns 结尾的纳秒精度属性。Stat 对象不应直接使用 new 关键字创建。

【Objects returned from fs.stat(), fs.lstat(), fs.fstat(), and their synchronous counterparts are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of number, and the object will contain additional nanosecond-precision properties suffixed with Ns. Stat objects are not to be created directly using the new keyword.】

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.isBlockDevice()#>

如果 <fs.Stats> 对象描述的是块设备,则返回 true

【Returns true if the <fs.Stats> object describes a block device.】

stats.isCharacterDevice()#>

如果 <fs.Stats> 对象描述的是字符设备,则返回 true

【Returns true if the <fs.Stats> object describes a character device.】

stats.isDirectory()#>

如果 <fs.Stats> 对象描述的是文件系统目录,则返回 true

【Returns true if the <fs.Stats> object describes a file system directory.】

如果从对符号链接调用 fs.lstat() 获取了 <fs.Stats> 对象,而该符号链接指向一个目录,则此方法将返回 false。这是因为 fs.lstat() 返回的是关于符号链接本身的信息,而不是它解析到的路径的信息。

【If the <fs.Stats> object was obtained from calling fs.lstat() on a symbolic link which resolves to a directory, this method will return false. This is because fs.lstat() returns information about a symbolic link itself and not the path it resolves to.】

stats.isFIFO()#>

如果 <fs.Stats> 对象描述的是先进先出 (FIFO) 管道,则返回 true

【Returns true if the <fs.Stats> object describes a first-in-first-out (FIFO) pipe.】

stats.isFile()#>

如果 <fs.Stats> 对象描述的是普通文件,则返回 true

【Returns true if the <fs.Stats> object describes a regular file.】

stats.isSocket()#>

如果 <fs.Stats> 对象描述的是套接字,则返回 true

【Returns true if the <fs.Stats> object describes a socket.】

stats.isSymbolicLink()#>

如果 <fs.Stats> 对象描述的是符号链接,则返回 true

【Returns true if the <fs.Stats> object describes a symbolic link.】

此方法仅在使用 fs.lstat() 时有效。

【This method is only valid when using fs.lstat().】

stats.dev#>

包含文件的设备的数字标识符。

【The numeric identifier of the device containing the file.】

stats.ino#>

文件的文件系统特定“索引节点”编号。

【The file system specific "Inode" number for the file.】

stats.mode#>

描述文件类型和模式的位字段。

【A bit-field describing the file type and mode.】

stats.nlink#>

文件存在的硬链接数。

【The number of hard-links that exist for the file.】

stats.uid#>

拥有文件的用户的数字用户标识符 (POSIX)。

【The numeric user identifier of the user that owns the file (POSIX).】

stats.gid#>

拥有文件的群组的数字群组标识符 (POSIX)。

【The numeric group identifier of the group that owns the file (POSIX).】

stats.rdev#>

如果文件代表设备,则为数字设备标识符。

【A numeric device identifier if the file represents a device.】

stats.size#>

文件的大小(以字节为单位)。

【The size of the file in bytes.】

如果底层文件系统不支持获取文件大小,则此值将为 0

【If the underlying file system does not support getting the size of the file, this will be 0.】

stats.blksize#>

i/o 操作的文件系统块大小。

【The file system block size for i/o operations.】

stats.blocks#>

为此文件分配的块数。

【The number of blocks allocated for this file.】

stats.atimeMs#>

表示上次访问此文件的时间戳,以自 POSIX 纪元以来的毫秒数表示。

【The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch.】

stats.mtimeMs#>

表示此文件上次修改时间的时间戳,以自 POSIX 纪元以来的毫秒数表示。

【The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch.】

stats.ctimeMs#>

表示文件状态最后一次更改的时间戳,以自 POSIX 纪元以来的毫秒为单位。

【The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch.】

stats.birthtimeMs#>

表示此文件创建时间的时间戳,以自 POSIX 纪元以来的毫秒为单位。

【The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch.】

stats.atimeNs#>

仅在将 bigint: true 传递给生成对象的方法时存在。 表示上次访问此文件的时间戳,以纳秒为单位,自 POSIX 纪元以来的时间。

【Only present when bigint: true is passed into the method that generates the object. The timestamp indicating the last time this file was accessed expressed in nanoseconds since the POSIX Epoch.】

stats.mtimeNs#>

仅在将 bigint: true 传递给生成对象的方法时存在。 表示此文件上次修改时间的时间戳,以自 POSIX 纪元以来的纳秒为单位。

【Only present when bigint: true is passed into the method that generates the object. The timestamp indicating the last time this file was modified expressed in nanoseconds since the POSIX Epoch.】

stats.ctimeNs#>

仅在将 bigint: true 传递给生成对象的方法时才会出现。该时间戳表示文件状态最后一次更改的时间,以自 POSIX 纪元以来的纳秒为单位。

【Only present when bigint: true is passed into the method that generates the object. The timestamp indicating the last time the file status was changed expressed in nanoseconds since the POSIX Epoch.】

stats.birthtimeNs#>

仅在将 bigint: true 传递给生成对象的方法时存在。该时间戳表示此文件的创建时间,以自 POSIX 纪元以来的纳秒为单位。

【Only present when bigint: true is passed into the method that generates the object. The timestamp indicating the creation time of this file expressed in nanoseconds since the POSIX Epoch.】

stats.atime#>

指示最后一次访问此文件的时间戳。

【The timestamp indicating the last time this file was accessed.】

stats.mtime#>

指示最后一次修改此文件的时间戳。

【The timestamp indicating the last time this file was modified.】

stats.ctime#>

指示最后一次更改文件状态的时间戳。

【The timestamp indicating the last time the file status was changed.】

stats.birthtime#>

指示此文件创建时间的时间戳。

【The timestamp indicating the creation time of this file.】

统计时间值#>

【Stat time values】

atimeMsmtimeMsctimeMsbirthtimeMs 属性是数值类型,用于保存对应时间的毫秒值。它们的精度取决于平台。当在生成该对象的方法中传入 bigint: true 时,这些属性将为 大整数,否则为 数字

【The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are numeric values that hold the corresponding times in milliseconds. Their precision is platform specific. When bigint: true is passed into the method that generates the object, the properties will be bigints, otherwise they will be numbers.】

atimeNsmtimeNsctimeNsbirthtimeNs 属性是 大整数,用于以纳秒为单位保存对应的时间。它们仅在向生成对象的方法传入 bigint: true 时才会出现。它们的精度取决于平台。

【The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are bigints that hold the corresponding times in nanoseconds. They are only present when bigint: true is passed into the method that generates the object. Their precision is platform specific.】

atimemtimectimebirthtimeDate 对象的各种时间的备用表示。Date 和数字值之间没有关联。分配一个新的数字值或更改 Date 值,不会反映在对应的备用表示中。

统计对象中的时间具有以下语义:

【The times in the stat object have the following semantics:】

  • atime “访问时间”:文件数据最后一次被访问的时间。可被 mknod(2)、utimes(2) 和 read(2) 系统调用修改。
  • mtime “修改时间”:文件数据最后被修改的时间。由 mknod(2)、utimes(2) 和 write(2) 系统调用更改。
  • ctime “更改时间”:文件状态最后一次更改的时间(inode 数据修改)。可由 chmod(2)、chown(2)、link(2)、mknod(2)、rename(2)、unlink(2)、utimes(2)、read(2) 和 write(2) 系统调用修改。
  • birthtime “创建时间”:文件创建的时间。文件创建时设置一次。在不支持 birthtime 的文件系统上,该字段可能会存储 ctime1970-01-01T00:00Z(即 Unix 纪元时间戳 0)。在这种情况下,该值可能大于 atimemtime。在 Darwin 和其他 FreeBSD 变体上,如果使用 utimes(2) 系统调用显式将 atime 设置为早于当前 birthtime 的值,也会进行设置。

在 Node.js 0.12 之前,Windows 系统上的 ctime 保存了 birthtime。从 0.12 版本开始,ctime 并不是“创建时间”,在 Unix 系统上,它也从来不是。

【Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As of 0.12, ctime is not "creation time", and on Unix systems, it never was.】

类:fs.StatFs#>

【Class: fs.StatFs

提供有关已安装文件系统的信息。

【Provides information about a mounted file system.】

fs.statfs() 及其同步对应方法返回的对象都是这种类型。如果传递给这些方法的 options 中的 biginttrue,则数值将是 bigint 而不是 number

【Objects returned from fs.statfs() and its synchronous counterpart are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of 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
} 
statfs.bavail#>

非特权用户可用的空闲块。

【Free blocks available to unprivileged users.】

statfs.bfree#>

文件系统中的空闲块。

【Free blocks in file system.】

statfs.blocks#>

文件系统中的总数据块。

【Total data blocks in file system.】

statfs.bsize#>

最佳传输块大小。

【Optimal transfer block size.】

statfs.ffree#>

文件系统中的空闲文件节点。

【Free file nodes in file system.】

statfs.files#>

文件系统中的文件节点总数。

【Total file nodes in file system.】

statfs.type#>

文件系统的类型。

【Type of file system.】

类:fs.WriteStream#>

【Class: fs.WriteStream

使用 fs.createWriteStream() 函数创建并返回 <fs.WriteStream> 的实例。

【Instances of <fs.WriteStream> are created and returned using the fs.createWriteStream() function.】

事件:'close'#>

【Event: 'close'

<fs.WriteStream> 的底层文件描述符已关闭时触发。

【Emitted when the <fs.WriteStream>'s underlying file descriptor has been closed.】

事件:'open'#>

【Event: 'open'

<fs.WriteStream> 的文件被打开时触发。

【Emitted when the <fs.WriteStream>'s file is opened.】

事件:'ready'#>

【Event: 'ready'

<fs.WriteStream> 可以使用时触发。

【Emitted when the <fs.WriteStream> is ready to be used.】

'open' 之后立即触发。

【Fires immediately after 'open'.】

writeStream.bytesWritten#>

到目前为止写入的字节数。不包括仍在排队等待写入的数据。

【The number of bytes written so far. Does not include data that is still queued for writing.】

writeStream.close([callback])#>

关闭 writeStream。可选择接受一个回调函数,该回调函数将在 writeStream 关闭后执行。

【Closes writeStream. Optionally accepts a callback that will be executed once the writeStream is closed.】

writeStream.path#>

流写入的文件路径,如 fs.createWriteStream() 的第一个参数所指定。如果 path 作为字符串传入,则 writeStream.path 将是一个字符串。如果 path 作为 <Buffer> 传入,则 writeStream.path 将是一个 <Buffer>

【The path to the file the stream is writing to as specified in the first argument to fs.createWriteStream(). If path is passed as a string, then writeStream.path will be a string. If path is passed as a <Buffer>, then writeStream.path will be a <Buffer>.】

writeStream.pending#>

如果底层文件尚未打开,即在触发 'ready' 事件之前,该属性为 true

【This property is true if the underlying file has not been opened yet, i.e. before the 'ready' event is emitted.】

fs.constants#>

返回一个包含文件系统操作常用常量的对象。

【Returns an object containing commonly used constants for file system operations.】

文件系统常量#>

【FS constants】

以下常量由 fs.constantsfsPromises.constants 导出。

【The following constants are exported by fs.constants and fsPromises.constants.】

并非每个常量在每个操作系统上都可用;这对于 Windows 尤为重要,因为许多特定于 POSIX 的定义在 Windows 上不可用。对于可移植的应用,建议在使用之前检查它们是否存在。

【Not every constant will be available on every operating system; this is especially important for Windows, where many of the POSIX specific definitions are not available. For portable applications it is recommended to check for their presence before use.】

要使用多个常量,请使用按位或 | 运算符。

【To use more than one constant, use the bitwise OR | operator.】

示例:

【Example:】

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) => {
  // ...
}); 

文件访问常量#>

【File access constants】

以下常量用于作为传递给 fsPromises.access()fs.access()fs.accessSync()mode 参数。

【The following constants are meant for use as the mode parameter passed to fsPromises.access(), fs.access(), and fs.accessSync().】

常量 描述
F_OK 标志,表示文件对于调用进程是可见的。 这对于判断文件是否存在很有用,但不能说明 rwx 权限。如果未指定模式,默认使用此标志。
R_OK 标志,表示调用进程可以读取该文件。
W_OK 标志,表示调用进程可以写入该文件。
X_OK 标志,表示调用进程可以执行该文件。在 Windows 上无效 (行为类似 fs.constants.F_OK)。

这些定义在 Windows 上也可用。

【The definitions are also available on Windows.】

文件复制常量#>

【File copy constants】

以下常量用于 fs.copyFile()

【The following constants are meant for use with fs.copyFile().】

常量 描述
COPYFILE_EXCL 如果存在,当目标路径已存在时,复制操作将失败并返回错误。
COPYFILE_FICLONE 如果存在,复制操作将尝试创建写时复制(COW)reflink。如果底层平台不支持写时复制,则使用备用复制机制。
COPYFILE_FICLONE_FORCE 如果存在,复制操作将尝试创建写时复制(COW)reflink。如果底层平台不支持写时复制,则操作将失败并返回错误。

这些定义在 Windows 上也可用。

【The definitions are also available on Windows.】

文件打开常量#>

【File open constants】

以下常量用于 fs.open()

【The following constants are meant for use with fs.open().】

Constant Description
O_RDONLY Flag indicating to open a file for read-only access.
O_WRONLY Flag indicating to open a file for write-only access.
O_RDWR Flag indicating to open a file for read-write access.
O_CREAT Flag indicating to create the file if it does not already exist.
O_EXCL Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
O_NOCTTY Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
O_TRUNC Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
O_APPEND Flag indicating that data will be appended to the end of the file.
O_DIRECTORY Flag indicating that the open should fail if the path is not a directory.
O_NOATIME Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
O_NOFOLLOW Flag indicating that the open should fail if the path is a symbolic link.
O_SYNC Flag indicating that the file is opened for synchronized I/O with write operations waiting for file integrity.
O_DSYNC Flag indicating that the file is opened for synchronized I/O with write operations waiting for data integrity.
O_SYMLINK Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
O_DIRECT When set, an attempt will be made to minimize caching effects of file I/O.
O_NONBLOCK Flag indicating to open the file in nonblocking mode when possible.
UV_FS_O_FILEMAP When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.

在 Windows 上,只有 O_APPENDO_CREATO_EXCLO_RDONLYO_RDWRO_TRUNCO_WRONLYUV_FS_O_FILEMAP 可用。

【On Windows, only O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, and UV_FS_O_FILEMAP are available.】

文件类型常量#>

【File type constants】

以下常量用于与 <fs.Stats> 对象的 mode 属性一起使用,以确定文件的类型。

【The following constants are meant for use with the <fs.Stats> object's mode property for determining a file's type.】

常量 描述
S_IFMT 用于提取文件类型代码的位掩码。
S_IFREG 常规文件的文件类型常量。
S_IFDIR 目录的文件类型常量。
S_IFCHR 字符设备文件的文件类型常量。
S_IFBLK 块设备文件的文件类型常量。
S_IFIFO FIFO/管道的文件类型常量。
S_IFLNK 符号链接的文件类型常量。
S_IFSOCK 套接字的文件类型常量。

在 Windows 上,只有 S_IFCHRS_IFDIRS_IFLNKS_IFMTS_IFREG 可用。

【On Windows, only S_IFCHR, S_IFDIR, S_IFLNK, S_IFMT, and S_IFREG, are available.】

文件模式常量#>

【File mode constants】

以下常量用于与 <fs.Stats> 对象的 mode 属性一起使用,以确定文件的访问权限。

【The following constants are meant for use with the <fs.Stats> object's mode property for determining the access permissions for a file.】

Constant Description
S_IRWXU File mode indicating readable, writable, and executable by owner.
S_IRUSR File mode indicating readable by owner.
S_IWUSR File mode indicating writable by owner.
S_IXUSR File mode indicating executable by owner.
S_IRWXG File mode indicating readable, writable, and executable by group.
S_IRGRP File mode indicating readable by group.
S_IWGRP File mode indicating writable by group.
S_IXGRP File mode indicating executable by group.
S_IRWXO File mode indicating readable, writable, and executable by others.
S_IROTH File mode indicating readable by others.
S_IWOTH File mode indicating writable by others.
S_IXOTH File mode indicating executable by others.

在 Windows 上,只有 S_IRUSRS_IWUSR 可用。

【On Windows, only S_IRUSR and S_IWUSR are available.】

注意事项#>

【Notes】

回调和基于 promise 的操作的顺序#>

【Ordering of callback and promise-based operations】

因为它们是由底层的线程池异步执行的,所以在使用回调或基于 Promise 的方法时,无法保证执行顺序。

【Because they are executed asynchronously by the underlying thread pool, there is no guaranteed ordering when using either the callback or promise-based methods.】

例如,下面的情况容易出错,因为 fs.stat() 操作可能在 fs.rename() 操作之前完成:

【For example, the following is prone to error because the fs.stat() operation might complete before the fs.rename() operation:】

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)}`);
}); 

在调用另一个操作之前,等待一个操作的结果,以正确的顺序执行操作是非常重要的:

【It is important to correctly order the operations by awaiting the results of one before invoking the other:】

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');

或者,在使用回调 APIs 时,将 fs.stat() 调用移到 fs.rename() 操作的回调中:

【Or, when using the callback APIs, move the fs.stat() call into the callback of the fs.rename() operation:】

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)}`);
  });
});

文件路径#>

【File paths】

大多数 fs 操作接受可以以字符串、<Buffer> 或使用 file: 协议的 <URL> 对象形式指定的文件路径。

【Most fs operations accept file paths that may be specified in the form of a string, a <Buffer>, or a <URL> object using the file: protocol.】

字符串路径#>

【String paths】

字符串路径被解释为 UTF-8 字符序列,用于标识绝对或相对的文件名。相对路径将相对于当前工作目录解析,该目录由调用 process.cwd() 确定。

【String paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling process.cwd().】

在 POSIX 上使用绝对路径的示例:

【Example using an absolute path on 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()):

【Example using a relative path on POSIX (relative to 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();
} 

文件网址路径#>

【File URL paths】

对于大多数 node:fs 模块函数,pathfilename 参数可以通过 file: 协议作为 <URL> 对象传递。

【For most node:fs module functions, the path or filename argument may be passed as a <URL> object using the file: protocol.】

import { readFileSync } from 'node:fs';

readFileSync(new URL('file:///tmp/hello')); 

file: URL 总是绝对路径。

特定于平台的注意事项#>

【Platform-specific considerations】

在 Windows 上,带有主机名的 file: <URL> 会转换为 UNC 路径,而带有驱动器字母的 file: <URL> 会转换为本地绝对路径。没有主机名且没有驱动器字母的 file: <URL> 将会导致错误:

【On Windows, file: <URL>s with a host name convert to UNC paths, while file: <URL>s with drive letters convert to local absolute paths. file: <URL>s with no host name and no drive letter will result in an error:】

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>s 不被支持,并会导致错误:

【On all other platforms, file: <URL>s with a host name are unsupported and will result in an error:】

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> 会在所有平台上导致错误:

【A file: <URL> having encoded slash characters will result in an error on all platforms:】

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> 如果包含编码的反斜杠,将导致错误:

【On Windows, file: <URL>s having encoded backslash will result in an error:】

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 paths】

使用 <Buffer> 指定的路径主要在某些将文件路径视为不透明字节序列的 POSIX 操作系统上很有用。在这样的系统上,一个文件路径中可能包含使用多种字符编码的子序列。与字符串路径一样,<Buffer> 路径也可以是相对的或绝对的:

【Paths specified using a <Buffer> are useful primarily on certain POSIX operating systems that treat file paths as opaque byte sequences. On such systems, it is possible for a single file path to contain sub-sequences that use multiple character encodings. As with string paths, <Buffer> paths may be relative or absolute:】

在 POSIX 上使用绝对路径的示例:

【Example using an absolute path on 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();
} 

Windows 上的每个驱动器工作目录#>

【Per-drive working directories on Windows】

在 Windows 上,Node.js 遵循每个驱动器的工作目录概念。当使用不带反斜杠的驱动器路径时,可以观察到这种行为。例如,fs.readdirSync('C:\') 的返回结果可能与 fs.readdirSync('C:') 不同。更多信息,请参见 这个 MSDN 页面

【On Windows, Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example fs.readdirSync('C:\\') can potentially return a different result than fs.readdirSync('C:'). For more information, see this MSDN page.】

文件描述符#>

【File descriptors】

在 POSIX 系统中,对于每个进程,内核都会维护一个当前打开文件和资源的表。每个打开的文件都会分配一个简单的数字标识符,称为 文件描述符。在系统级别上,所有文件系统操作都使用这些文件描述符来识别和跟踪每个特定文件。Windows 系统使用一种不同但概念上类似的机制来跟踪资源。为了简化用户的操作,Node.js 把操作系统之间的差异抽象掉,并为所有打开的文件分配一个数字文件描述符。

【On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a file descriptor. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the differences between operating systems and assigns all open files a numeric file descriptor.】

基于回调的 fs.open() 方法和同步的 fs.openSync() 方法用于打开文件并分配一个新的文件描述符。一旦分配,文件描述符可以用于读取文件数据、写入文件数据或请求文件相关信息。

【The callback-based fs.open(), and synchronous fs.openSync() methods open a file and allocate a new file descriptor. Once allocated, the file descriptor may be used to read data from, write data to, or request information about the file.】

操作系统会限制在任意给定时间内可以打开的文件描述符数量,因此在操作完成后关闭描述符是至关重要的。如果不这样做,将导致内存泄漏,最终可能导致应用崩溃。

【Operating systems limit the number of file descriptors that may be open at any given time so it is critical to close the descriptor when operations are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash.】

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> 对象来代替数字文件描述符。这些对象由系统更好地管理,以确保资源不会泄漏。然而,在操作完成后仍然需要关闭它们:

【The promise-based APIs use a <FileHandle> object in place of the numeric file descriptor. These objects are better managed by the system to ensure that resources are not leaked. However, it is still required that they are closed when operations are completed:】

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();
} 

线程池使用#>

【Threadpool usage】

所有基于回调和 Promise 的文件系统 API(fs.FSWatcher() 除外)都使用 libuv 的线程池。这对于某些应用可能会产生意想不到的负面性能影响。有关更多信息,请参阅 UV_THREADPOOL_SIZE 文档。

【All callback and promise-based file system APIs (with the exception of fs.FSWatcher()) use libuv's threadpool. This can have surprising and negative performance implications for some applications. See the UV_THREADPOOL_SIZE documentation for more information.】

文件系统标志#>

【File system flags】

以下标志可在任何接受字符串的 flag 选项中使用。

【The following flags are available wherever the flag option takes a string.】

  • '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 也会返回错误。排他标志在网络文件系统上可能无法正常工作。

【The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to return an error if the path already exists. On POSIX, if the path is a symbolic link, using O_EXCL returns an error even if the link is to a path that does not exist. The exclusive flag might not work with network file systems.】

在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

【On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】

修改文件而不是替换它可能需要将 flag 选项设置为 'r+' 而不是默认的 'w'

【Modifying a file rather than replacing it may require the flag option to be set to 'r+' rather than the default 'w'.】

某些标志的行为是平台特定的。因此,在 macOS 和 Linux 上使用 'a+' 标志打开目录,如下面的例子所示,将会返回错误。相比之下,在 Windows 和 FreeBSD 上,会返回一个文件描述符或 FileHandle

【The behavior of some flags are platform-specific. As such, opening a directory on macOS and Linux with the 'a+' flag, as in the example below, will return an error. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle will be returned.】

// 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+' 标志打开已存在的隐藏文件进行写入。

【On Windows, opening an existing hidden file using the 'w' flag (either through fs.open(), fs.writeFile(), or fsPromises.open()) will fail with EPERM. Existing hidden files can be opened for writing with the 'r+' flag.】

可以调用 fs.ftruncate()filehandle.truncate() 来重置文件内容。

【A call to fs.ftruncate() or filehandle.truncate() can be used to reset the file contents.】

Node.js 中文网 - 粤ICP备13048890号