Node.js v20.11.1 文档


文件系统#

¥File system

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: 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 模块进行访问。

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

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.

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

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

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

¥All <FileHandle> objects are <EventEmitter>.

如果未使用 filehandle.close() 方法关闭 <FileHandle>,则它将尝试自动关闭文件描述符并触发进程警告,从而有助于防止内存泄漏。请不要依赖此行为,因为它可能不可靠并且该文件可能未被关闭。相反,始终显式关闭 <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>. 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)#
  • mode <integer> 文件模式位掩码。

    ¥mode <integer> the file mode bit mask.

  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

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

¥Modifies the permissions on the file. See chmod(2).

filehandle.chown(uid, gid)#
  • uid <integer> 文件的新所有者的用户 ID。

    ¥uid <integer> The file's new owner's user id.

  • gid <integer> 文件的新群组的组 ID。

    ¥gid <integer> The file's new group's group id.

  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

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

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

filehandle.close()#
  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

等待句柄上的任何未决操作完成后,关闭文件句柄。

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

<stream.Readable> 的 16 KiB 默认 highWaterMark 不同,此方法返回的流的默认 highWaterMark 为 64 KiB。

¥Unlike the 16 KiB default highWaterMark for a <stream.Readable>, the stream returned by this method has a default highWaterMark of 64 KiB.

options 可以包括 startend 值,以从文件中读取一定范围的字节,而不是整个文件。startend 均包含在内并从 0 开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围内。如果省略 start 或为 undefined,则 filehandle.createReadStream() 从当前的文件位置开始依次读取。encoding 可以是 <Buffer> 接受的任何一种。

¥options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If start is omitted or undefined, filehandle.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by <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+(而不是默认的 r)。encoding 可以是 <Buffer> 接受的任何一种。

¥options may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags open option to be set to r+ rather than the default r. The encoding can be any one of those accepted by <Buffer>.

如果将 autoClose 设置为 true(默认行为),则在 'error''finish' 时文件描述符将自动关闭。如果 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 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

将与文件关联的所有当前排队的 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> 将填充读取的文件数据的缓冲区。

    ¥buffer <Buffer> | <TypedArray> | <DataView> A buffer that will be filled with the file data read.

  • offset <integer> 缓冲区中开始填充的位置。

    ¥offset <integer> The location in the buffer at which to start filling.

  • length <integer> 读取的字节数。

    ¥length <integer> The number of bytes to read.

  • position <integer> | <null> 从文件开始读取数据的位置。如果为 null,则将从当前文件位置读取数据,并将更新该位置。如果 position 是整数,则当前文件位置将保持不变。

    ¥position <integer> | <null> The location where to begin reading data from the file. If null, data will be read from the current file position, and the position will be updated. If position is an integer, the current file position will remain unchanged.

  • 返回:<Promise> 成功时将使用具有以下两个属性的对象履行:

    ¥Returns: <Promise> Fulfills upon success with an object with two properties:

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

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

      ¥buffer <Buffer> | <TypedArray> | <DataView> A buffer that will be filled with the file data read. Default: Buffer.alloc(16384)

    • offset <integer> 缓冲区中开始填充的位置。默认值:0

      ¥offset <integer> The location in the buffer at which to start filling. Default: 0

    • length <integer> 读取的字节数。默认值:buffer.byteLength - offset

      ¥length <integer> The number of bytes to read. Default: buffer.byteLength - offset

    • position <integer> | <null> 从文件开始读取数据的位置。如果为 null,则将从当前文件位置读取数据,并将更新该位置。如果 position 是整数,则当前文件位置将保持不变。Default::null

      ¥position <integer> | <null> The location where to begin reading data from the file. If null, data will be read from the current file position, and the position will be updated. If position is an integer, the current file position will remain unchanged. Default:: null

  • 返回:<Promise> 成功时将使用具有以下两个属性的对象履行:

    ¥Returns: <Promise> Fulfills upon success with an object with two properties:

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

¥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> 将填充读取的文件数据的缓冲区。

    ¥buffer <Buffer> | <TypedArray> | <DataView> A buffer that will be filled with the file data read.

  • options <Object>

    • offset <integer> 缓冲区中开始填充的位置。默认值:0

      ¥offset <integer> The location in the buffer at which to start filling. Default: 0

    • length <integer> 读取的字节数。默认值:buffer.byteLength - offset

      ¥length <integer> The number of bytes to read. Default: buffer.byteLength - offset

    • position <integer> 从文件开始读取数据的位置。如果为 null,则将从当前文件位置读取数据,并将更新该位置。如果 position 是整数,则当前文件位置将保持不变。Default::null

      ¥position <integer> The location where to begin reading data from the file. If null, data will be read from the current file position, and the position will be updated. If position is an integer, the current file position will remain unchanged. Default:: null

  • 返回:<Promise> 成功时将使用具有以下两个属性的对象履行:

    ¥Returns: <Promise> Fulfills upon success with an object with two properties:

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

¥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 - 实验性的

¥Stability: 1 - Experimental

返回可用于读取文件数据的 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> 对象返回。否则,数据将为字符串。

    ¥Returns: <Promise> Fulfills upon a successful read with the contents of the file. If no encoding is specified (using options.encoding), the data is returned as a <Buffer> object. Otherwise, the data will be a string.

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

¥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>

filehandle.stat([options])#

filehandle.sync()#
  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

请求将打开文件描述符的所有数据刷新到存储设备。具体实现是操作系统和设备特定的。有关更多详细信息,请参阅 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> 引用的对象的文件系统时间戳,然后在成功时不带参数地履行 promise。

¥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 的起始位置。

    ¥offset <integer> The start position from within buffer where the data to write begins.

  • length <integer> 要从 buffer 写入的字节数。默认值:buffer.byteLength - offset

    ¥length <integer> The number of bytes from buffer to write. Default: buffer.byteLength - offset

  • position <integer> | <null> 要写入来自 buffer 的数据的文件的开头偏移量。如果 position 不是 number,则数据将被写入当前位置。有关更多详细信息,请参阅 POSIX pwrite(2) 文档。默认值:null

    ¥position <integer> | <null> The offset from the beginning of the file where the data from buffer should be written. If position is not a number, the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail. Default: null

  • 返回:<Promise>

    ¥Returns: <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

    ¥position <integer> | <null> The offset from the beginning of the file where the data from string should be written. If position is not a number the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail. Default: null

  • encoding <string> 预期的字符串编码。默认值:'utf8'

    ¥encoding <string> The expected string encoding. Default: 'utf8'

  • 返回:<Promise>

    ¥Returns: <Promise>

string 写入文件。如果 string 不是字符串,则 promise 使用错误拒绝。

¥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> 写入的字节数

    ¥bytesWritten <integer> the number of bytes written

  • buffer <string> 对被写入的 string 的引用。

    ¥buffer <string> a reference to the string written.

在同一个文件上多次使用 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> 对象。诺言一经成功就兑现了,没有任何争议。

¥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])#
  • buffers <Buffer[]> | <TypedArray[]> | <DataView[]>

  • position <integer> | <null> 要写入来自 buffers 的数据的文件的开头偏移量。如果 position 不是 number,则数据将被写入当前位置。默认值:null

    ¥position <integer> | <null> The offset from the beginning of the file where the data from buffers should be written. If position is not a number, the data will be written at the current position. Default: null

  • 返回:<Promise>

    ¥Returns: <Promise>

<ArrayBufferView> 的数组写入文件。

¥Write an array of <ArrayBufferView> to the file.

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

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

在不等待 promise 履行(或拒绝)的情况下对同一个文件多次调用 writev() 是不安全的。

¥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 - 实验性的

¥Stability: 1 - Experimental

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 就得到履行,但没有任何值。如果任何可访问性检查失败,则使用 <Error> 对象拒绝 promise。以下示例检查当前进程是否可以读写文件 /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 指定为已打开用于追加(使用 fsPromises.open())的 <FileHandle>

¥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> 要复制的源文件名

    ¥src <string> | <Buffer> | <URL> source filename to copy

  • dest <string> | <Buffer> | <URL> 复制操作的目标文件名

    ¥dest <string> | <Buffer> | <URL> destination filename of the copy operation

  • mode <integer> 指定复制操作行为的可选修饰符。可以创建一个由两个或多个值的按位或组成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)默认值:0

    ¥mode <integer> Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE) Default: 0.

    • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,则复制操作将失败。

      ¥fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.

    • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建写时复制引用链接。如果平台不支持写时复制,则使用后备复制机制。

      ¥fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.

    • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建写时复制引用链接。如果平台不支持写时复制,则该操作将失败。

      ¥fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.

  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

异步地将 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 - 实验性的

¥Stability: 1 - Experimental

  • src <string> | <URL> 要复制的源路径。

    ¥src <string> | <URL> source path to copy.

  • dest <string> | <URL> 要复制到的目标路径。

    ¥dest <string> | <URL> destination path to copy to.

  • options <Object>

    • dereference <boolean> 取消引用符号链接。默认值:false

      ¥dereference <boolean> dereference symlinks. Default: false.

    • errorOnExist <boolean>forcefalse 且目标存在时,抛出错误。默认值:false

      ¥errorOnExist <boolean> when force is false, and the destination exists, throw an error. Default: false.

    • filter <Function> 过滤复制文件/目录的函数。返回 true 则复制条目,返回 false 则忽略它。忽略目录时,其所有内容也将被跳过。还可以返回解析为 truefalse 默认值的 Promiseundefined

      ¥filter <Function> Function to filter copied files/directories. Return true to copy the item, false to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a Promise that resolves to true or false Default: undefined.

    • force <boolean> 覆盖现有文件或目录。如果将此设置为 false 并且目标存在,则复制操作将忽略错误。使用 errorOnExist 选项更改此行为。默认值:true

      ¥force <boolean> overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior. Default: true.

    • mode <integer> 复制操作的修饰符。默认值:0。参见 fsPromises.copyFile()mode 标志。

      ¥mode <integer> modifiers for copy operation. Default: 0. See mode flag of fsPromises.copyFile().

    • preserveTimestamps <boolean> 当为 true 时,则 src 的时间戳将被保留。默认值:false

      ¥preserveTimestamps <boolean> When true timestamps from src will be preserved. Default: false.

    • recursive <boolean> 递归复制目录默认:false

      ¥recursive <boolean> copy directories recursively Default: false

    • verbatimSymlinks <boolean> 当为 true 时,则符号链接的路径解析将被跳过。默认值:false

      ¥verbatimSymlinks <boolean> When true, path resolution for symlinks will be skipped. Default: false

  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

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

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

当将目录复制到另一个目录时,不支持 globs,并且行为类似于 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)#

更改符号链接的权限。

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

  • path <string> | <Buffer> | <URL>

  • options <Object> | <integer>

  • 返回:<Promise> 成功后,如果 recursivefalse,则使用 undefined 履行;如果 recursivetrue,则使用创建的第一个目录路径履行。

    ¥Returns: <Promise> Upon success, fulfills with undefined if recursive is false, or the first directory path created if recursive is true.

异步地创建目录。

¥Asynchronously creates a directory.

可选的 options 参数可以是指定 mode(权限和粘性位)的整数,也可以是具有 mode 属性和 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])#

  • path <string> | <Buffer> | <URL>

  • options <Object>

    • encoding <string> | <null> 默认值:'utf8'

      ¥encoding <string> | <null> Default: 'utf8'

    • bufferSize <number> 当从目录读取时,在内部缓冲的目录条目数。值越大,性能越好,但内存使用率越高。默认值:32

      ¥bufferSize <number> Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. Default: 32

    • recursive <boolean> 已解析的 Dir 将是包含所有子文件和目录的 <AsyncIterable>。默认值:false

      ¥recursive <boolean> Resolved Dir will be an <AsyncIterable> containing all sub files and directories. Default: false

  • 返回:<Promise> 满足 <fs.Dir>

    ¥Returns: <Promise> Fulfills with an <fs.Dir>.

异步地打开目录进行迭代扫描。有关更多详细信息,请参阅 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'

      ¥encoding <string> Default: 'utf8'

    • withFileTypes <boolean> 默认值:false

      ¥withFileTypes <boolean> Default: false

    • recursive <boolean> 如果是 true,则递归读取目录的内容。在递归模式下,它将列出所有文件、子文件和目录。默认值:false

      ¥recursive <boolean> If true, reads the contents of a directory recursively. In recursive mode, it will list all files, sub files, and directories. Default: false.

  • 返回:<Promise> 使用目录中文件的名称数组(不包括 '.''..')履行。

    ¥Returns: <Promise> Fulfills with an array of the names of the files in the directory excluding '.' and '..'.

读取目录的内容。

¥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 的成功兑现了这一 promise。

¥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

      ¥maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js retries the operation with a linear backoff wait of retryDelay milliseconds longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true. Default: 0.

    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作将在失败时重试。默认值:false。已弃用。

      ¥recursive <boolean> If true, perform a recursive directory removal. In recursive mode, operations are retried on failure. Default: false. Deprecated.

    • retryDelay <integer> 重试之间等待的时间(以毫秒为单位)。如果 recursive 选项不为 true,则忽略此选项。默认值:100

      ¥retryDelay <integer> The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true. Default: 100.

  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

删除由 path 标识的目录。

¥Removes the directory identified by path.

在文件(而不是目录)上使用 fsPromises.rmdir() 会导致 promise 被拒绝,在 Windows 上使用 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 命令的行为,则使用具有选项 { recursive: true, force: true }fsPromises.rm()

¥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

      ¥force <boolean> When true, exceptions will be ignored if path does not exist. Default: false.

    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 将在每次尝试时以 retryDelay 毫秒的线性退避等待时间重试该操作。此选项表示重试次数。如果 recursive 选项不为 true,则忽略此选项。默认值:0

      ¥maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js will retry the operation with a linear backoff wait of retryDelay milliseconds longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true. Default: 0.

    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作将在失败时重试。默认值:false

      ¥recursive <boolean> If true, perform a recursive directory removal. In recursive mode operations are retried on failure. Default: false.

    • retryDelay <integer> 重试之间等待的时间(以毫秒为单位)。如果 recursive 选项不为 true,则忽略此选项。默认值:100

      ¥retryDelay <integer> The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true. Default: 100.

  • 返回:<Promise> 成功时将使用 undefined 履行。

    ¥Returns: <Promise> Fulfills with undefined upon success.

删除文件和目录(在标准 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' 这样的数字字符串。

    ¥Values can be either numbers representing Unix epoch time, Dates, or a numeric string like '123456789.0'.

  • 如果该值不能转换为数字,或者是 NaNInfinity-Infinity,则会抛出 Error

    ¥If the value can not be converted to a number, or is NaN, Infinity, or -Infinity, an Error will be thrown.

fsPromises.watch(filename[, options])#

  • filename <string> | <Buffer> | <URL>

  • options <string> | <Object>

    • persistent <boolean> 指示只要正在监视文件,进程是否应继续运行。默认值:true

      ¥persistent <boolean> Indicates whether the process should continue to run as long as files are being watched. Default: true.

    • recursive <boolean> 指示是应监视所有子目录,还是仅监视当前目录。这在指定目录时适用,并且仅适用于受支持的平台(参见 caveats)。默认值:false

      ¥recursive <boolean> Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See caveats). Default: false.

    • encoding <string> 指定用于传给监听器的文件名的字符编码。默认值:'utf8'

      ¥encoding <string> Specifies the character encoding to be used for the filename passed to the listener. Default: 'utf8'.

    • signal <AbortSignal> 用于指示监视器何时应停止的 <AbortSignal>

      ¥signal <AbortSignal> An <AbortSignal> used to signal when the watcher should stop.

  • 返回:<AsyncIterator> 个具有以下属性的对象:

    ¥Returns: <AsyncIterator> of objects with the properties:

返回异步迭代器,其监视 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() 的所有 caveats 也适用于 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.

在同一个文件上多次使用 fsPromises.writeFile() 而不等待 promise 被解决是不安全的。

¥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.

写入(不推荐)

¥write (NOT RECOMMENDED)

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

写入(推荐)

¥write (RECOMMENDED)

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

读取(不推荐)

¥read (NOT RECOMMENDED)

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

读取(推荐)

¥read (RECOMMENDED)

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

上面的 "不建议" 示例检查可访问性,然后使用该文件;"recommended" 示例更好,因为它们直接使用文件并处理错误(如果有)。

¥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:

  • 所有者可以读取、写入、以及执行文件。

    ¥The owner may read, write, and execute the file.

  • 群组可以读取和写入文件。

    ¥The group may read and write the file.

  • 其他人可以读取和执行文件。

    ¥Others may read and execute the file.

在需要文件模式的地方使用原始数字时,任何大于 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 上只能修改写权限,没有实现 group、owner、其他权限的区分。

¥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 是可选的整数,用于指定复制操作的行为。可以创建由两个或多个值的按位或组成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)。

¥mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

  • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,则复制操作将失败。

    ¥fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.

  • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建写时复制引用链接。如果平台不支持写时复制,则使用后备复制机制。

    ¥fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.

  • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建写时复制引用链接。如果平台不支持写时复制,则该操作将失败。

    ¥fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.

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 - 实验性的

¥Stability: 1 - Experimental

  • src <string> | <URL> 要复制的源路径。

    ¥src <string> | <URL> source path to copy.

  • dest <string> | <URL> 要复制到的目标路径。

    ¥dest <string> | <URL> destination path to copy to.

  • options <Object>

    • dereference <boolean> 取消引用符号链接。默认值:false

      ¥dereference <boolean> dereference symlinks. Default: false.

    • errorOnExist <boolean>forcefalse 且目标存在时,抛出错误。默认值:false

      ¥errorOnExist <boolean> when force is false, and the destination exists, throw an error. Default: false.

    • filter <Function> 过滤复制文件/目录的函数。返回 true 则复制条目,返回 false 则忽略它。忽略目录时,其所有内容也将被跳过。还可以返回解析为 truefalse 默认值的 Promiseundefined

      ¥filter <Function> Function to filter copied files/directories. Return true to copy the item, false to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a Promise that resolves to true or false Default: undefined.

    • force <boolean> 覆盖现有文件或目录。如果将此设置为 false 并且目标存在,则复制操作将忽略错误。使用 errorOnExist 选项更改此行为。默认值:true

      ¥force <boolean> overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior. Default: true.

    • mode <integer> 复制操作的修饰符。默认值:0。参见 fs.copyFile()mode 标志。

      ¥mode <integer> modifiers for copy operation. Default: 0. See mode flag of fs.copyFile().

    • preserveTimestamps <boolean> 当为 true 时,则 src 的时间戳将被保留。默认值:false

      ¥preserveTimestamps <boolean> When true timestamps from src will be preserved. Default: false.

    • recursive <boolean> 递归复制目录默认:false

      ¥recursive <boolean> copy directories recursively Default: false

    • verbatimSymlinks <boolean> 当为 true 时,则符号链接的路径解析将被跳过。默认值:false

      ¥verbatimSymlinks <boolean> When true, path resolution for symlinks will be skipped. Default: false

  • callback <Function>

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

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

当将目录复制到另一个目录时,不支持 globs,并且行为类似于 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])#

<stream.Readable> 的 16 KiB 默认 highWaterMark 不同,此方法返回的流的默认 highWaterMark 为 64 KiB。

¥Unlike the 16 KiB default highWaterMark for a <stream.Readable>, the stream returned by this method has a default highWaterMark of 64 KiB.

options 可以包括 startend 值,以从文件中读取一定范围的字节,而不是整个文件。startend 均包含在内并从 0 开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围内。如果指定了 fd 并且 start 被省略或 undefined,则 fs.createReadStream() 从当前文件位置顺序读取。encoding 可以是 <Buffer> 接受的任何一种。

¥options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is omitted or undefined, fs.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by <Buffer>.

如果指定了 fd,则 ReadStream 将忽略 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 设置文件模式(权限和粘滞位),但前提是文件已创建。

¥mode sets the file mode (permission and sticky bits), but only if the file was created.

读取 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> 接受的任何一种。

¥options may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags option to be set to r+ rather than the default w. The encoding can be any one of those accepted by <Buffer>.

如果将 autoClose 设置为 true(默认行为),则在 'error''finish' 时文件描述符将自动关闭。如果 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 实现。在没有 writev() 的情况下覆盖 write() 会降低性能,因为某些优化 (_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()

¥Stability: 0 - Deprecated: Use fs.stat() or fs.access() instead.

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

¥Test whether or not 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() 的原因之一。

¥The parameters for this callback are not consistent with other Node.js callbacks. Normally, the first parameter to a Node.js callback is an err parameter, optionally followed by other parameters. The fs.exists() callback has only one boolean parameter. This is one reason fs.access() is recommended instead of fs.exists().

不建议在调用 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.

写入(不推荐)

¥write (NOT RECOMMENDED)

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

写入(推荐)

¥write (RECOMMENDED)

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

读取(不推荐)

¥read (NOT RECOMMENDED)

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

读取(推荐)

¥read (RECOMMENDED)

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

上面的 "不建议" 示例检查文件是否存在,然后使用该文件;"recommended" 示例更好,因为它们直接使用文件并处理错误(如果有)。

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

更改符号链接的权限。除了可能的异常之外,没有为完成回调提供任何参数。

¥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 是符号链接,则被统计的是链接本身,而不是它引用的文件。

¥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 为假且目录存在,则会发生 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()

¥mode sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see 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 - 实验性的

¥Stability: 1 - Experimental

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

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

创建 <Blob> 后不得修改该文件。任何修改都会导致读取 <Blob> 数据失败并出现 DOMException 错误。Blob 创建时和每次读取前对文件进行同步 stat 操作,以检测文件数据是否在磁盘上被修改。

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

  • path <string> | <Buffer> | <URL>

  • options <Object>

    • encoding <string> | <null> 默认值:'utf8'

      ¥encoding <string> | <null> Default: 'utf8'

    • bufferSize <number> 当从目录读取时,在内部缓冲的目录条目数。值越大,性能越好,但内存使用率越高。默认值:32

      ¥bufferSize <number> Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. Default: 32

    • recursive <boolean> 默认值:false

      ¥recursive <boolean> Default: false

  • callback <Function>

异步地打开目录。有关更多详细信息,请参阅 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 <integer>

  • buffer <Buffer> | <TypedArray> | <DataView> 数据将写入的缓冲区。

    ¥buffer <Buffer> | <TypedArray> | <DataView> The buffer that the data will be written to.

  • offset <integer> 要写入数据的 buffer 中的位置。

    ¥offset <integer> The position in buffer to write the data to.

  • length <integer> 读取的字节数。

    ¥length <integer> The number of bytes to read.

  • position <integer> | <bigint> | <null> 指定从文件中开始读取的位置。如果 positionnull-1 ,则将从当前文件位置读取数据,并更新文件位置。如果 position 是整数,则文件位置将保持不变。

    ¥position <integer> | <bigint> | <null> Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.

  • callback <Function>

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() 版本被调用,则返回具有 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[, 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. 任何指定的文件描述符都必须支持读取。

    ¥Any specified file descriptor has to support reading.

  2. 如果将文件描述符指定为 path,则它将不会自动关闭。

    ¥If a file descriptor is specified as the path, it will not be closed automatically.

  3. 读数将从当前位置开始。例如,如果文件已经具有 'Hello World' 并且使用文件描述符读取了 6 个字节,则使用相同文件描述符调用 fs.readFile() 将给出 'World',而不是 'Hello World'

    ¥The reading will begin at the current position. For example, if the file already had 'Hello World' and six bytes are read with the file descriptor, the call to fs.readFile() with the same file descriptor, would give 'World', rather than '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 提供了更多信息,并详细分析了 fs.readFile() 在不同 Node.js 版本中针对多种文件大小的性能。

¥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',则从当前位置读取数据。

¥position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.

回调将被赋予三个参数:errbytesReadbuffersbytesRead 是从文件中读取的字节数。

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

如果此方法作为其 util.promisify() 版本被调用,则返回具有 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. 在不区分大小写的文件系统上不执行大小写转换。

    ¥No case conversion is performed on case-insensitive file systems.

  2. 符号链接的最大数量与平台无关,并且通常(远)高于原生 realpath(3) 实现支持的数量。

    ¥The maximum number of symbolic links is platform-independent and generally (much) higher than what the native realpath(3) implementation supports.

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.

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

      ¥maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js retries the operation with a linear backoff wait of retryDelay milliseconds longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true. Default: 0.

    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作将在失败时重试。默认值:false。已弃用。

      ¥recursive <boolean> If true, perform a recursive directory removal. In recursive mode, operations are retried on failure. Default: false. Deprecated.

    • retryDelay <integer> 重试之间等待的时间(以毫秒为单位)。如果 recursive 选项不为 true,则忽略此选项。默认值:100

      ¥retryDelay <integer> The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true. Default: 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 命令的行为,则使用具有选项 { recursive: true, force: true }fs.rm()

¥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

      ¥force <boolean> When true, exceptions will be ignored if path does not exist. Default: false.

    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 将在每次尝试时以 retryDelay 毫秒的线性退避等待时间重试该操作。此选项表示重试次数。如果 recursive 选项不为 true,则忽略此选项。默认值:0

      ¥maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js will retry the operation with a linear backoff wait of retryDelay milliseconds longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true. Default: 0.

    • recursive <boolean> 如果为 true,则执行递归删除。在递归模式下,操作将在失败时重试。默认值:false

      ¥recursive <boolean> If true, perform a recursive removal. In recursive mode operations are retried on failure. Default: false.

    • retryDelay <integer> 重试之间等待的时间(以毫秒为单位)。如果 recursive 选项不为 true,则忽略此选项。默认值:100

      ¥retryDelay <integer> The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true. Default: 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)#

异步统计(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.stat() follows symbolic links. Use fs.lstat() to look at the links themselves.

不建议在调用 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' 时,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()

¥fs.unlink() will not work on a directory, empty or otherwise. To remove a directory, use 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' 这样的数字字符串。

    ¥Values can be either numbers representing Unix epoch time in seconds, Dates, or a numeric string like '123456789.0'.

  • 如果该值不能转换为数字,或者是 NaNInfinity-Infinity,则会抛出 Error

    ¥If the value can not be converted to a number, or is NaN, Infinity, or -Infinity, an Error will be thrown.

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

  • filename <string> | <Buffer> | <URL>

  • options <string> | <Object>

    • persistent <boolean> 指示只要正在监视文件,进程是否应继续运行。默认值:true

      ¥persistent <boolean> Indicates whether the process should continue to run as long as files are being watched. Default: true.

    • recursive <boolean> 指示是应监视所有子目录,还是仅监视当前目录。这在指定目录时适用,并且仅适用于受支持的平台(参见 caveats)。默认值:false

      ¥recursive <boolean> Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See caveats). Default: false.

    • encoding <string> 指定用于传给监听器的文件名的字符编码。默认值:'utf8'

      ¥encoding <string> Specifies the character encoding to be used for the filename passed to the listener. Default: 'utf8'.

    • signal <AbortSignal> 允许使用 AbortSignal 关闭监视器。

      ¥signal <AbortSignal> allows closing the watcher with an AbortSignal.

  • listener <Function> | <undefined> 默认值:undefined

    ¥listener <Function> | <undefined> Default: undefined

  • 返回:<fs.FSWatcher>

    ¥Returns: <fs.FSWatcher>

监视 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 跨平台并非 100% 一致,并且在某些情况下不可用。

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

    ¥On Linux systems, this uses inotify(7).

  • 在 BSD 系统上,这使用 kqueue(2)

    ¥On BSD systems, this uses kqueue(2).

  • 在 macOS 上,这对文件使用 kqueue(2),对目录使用 FSEvents

    ¥On macOS, this uses kqueue(2) for files and FSEvents for directories.

  • 在 SunOS 系统(包括 Solaris 和 SmartOS)上,这使用 event ports

    ¥On SunOS systems (including Solaris and SmartOS), this uses event ports.

  • 在 Windows 系统上,此功能取决于 ReadDirectoryChangesW

    ¥On Windows systems, this feature depends on ReadDirectoryChangesW.

  • 在 AIX 系统上,此功能依赖于必须启用的 AHAFS

    ¥On AIX systems, this feature depends on AHAFS, which must be enabled.

  • 在 IBM i 系统上,不支持此功能。

    ¥On IBM i systems, this feature is not supported.

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

¥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(),它使用 stat 轮询,但这种方法较慢且不太可靠。

¥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。如果监视路径被删除并重新创建,则会为其分配一个新的索引节点。watch 将触发删除事件,但会继续监视原始 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 文件在文件的生命周期内保留相同的索引节点。在 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

仅在 Linux、macOS、Windows 和 AIX 上支持在回调中提供 filename 参数。即使在支持的平台上,也不能保证始终提供 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 具有两个参数,当前的统计对象和上一个统计对象:

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

这些统计对象是 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 Epoch)。如果文件是后来创建的,则将使用最新的统计对象再次调用监听器。这是自 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:

  • 文件被删除,然后恢复

    ¥the file is deleted, followed by a restore

  • 文件被重命名,然后再次重命名回其原始名称

    ¥the file is renamed and then renamed a second time back to its original name

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

buffer 写入 fd 指定的文件。

¥Write buffer to the file specified by fd.

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

¥offset determines the part of the buffer to be written, and length is an integer specifying the number of bytes to write.

position 指从文件开头数据应被写入的偏移量。如果 typeof position !== 'number',则数据将写入当前位置。请参见 pwrite(2)

¥position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position. See 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() 版本被调用,则返回具有 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)

¥position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number' the data will be written at the current position. See pwrite(2).

encoding 是预期的字符串编码。

¥encoding is the expected string 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',则数据将写入当前位置。

¥position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.

回调将被赋予三个参数: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])#

同步地复制 srcdest。默认情况下,如果 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 是可选的整数,用于指定复制操作的行为。可以创建由两个或多个值的按位或组成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)。

¥mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

  • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,则复制操作将失败。

    ¥fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.

  • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建写时复制引用链接。如果平台不支持写时复制,则使用后备复制机制。

    ¥fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.

  • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建写时复制引用链接。如果平台不支持写时复制,则该操作将失败。

    ¥fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.

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 - 实验性的

¥Stability: 1 - Experimental

  • src <string> | <URL> 要复制的源路径。

    ¥src <string> | <URL> source path to copy.

  • dest <string> | <URL> 要复制到的目标路径。

    ¥dest <string> | <URL> destination path to copy to.

  • options <Object>

    • dereference <boolean> 取消引用符号链接。默认值:false

      ¥dereference <boolean> dereference symlinks. Default: false.

    • errorOnExist <boolean>forcefalse 且目标存在时,抛出错误。默认值:false

      ¥errorOnExist <boolean> when force is false, and the destination exists, throw an error. Default: false.

    • filter <Function> 过滤复制文件/目录的函数。返回 true 则复制条目,返回 false 则忽略它。忽略目录时,其所有内容也将被跳过。默认值:undefined

      ¥filter <Function> Function to filter copied files/directories. Return true to copy the item, false to ignore it. When ignoring a directory, all of its contents will be skipped as well. Default: undefined

    • force <boolean> 覆盖现有文件或目录。如果将此设置为 false 并且目标存在,则复制操作将忽略错误。使用 errorOnExist 选项更改此行为。默认值:true

      ¥force <boolean> overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior. Default: true.

    • mode <integer> 复制操作的修饰符。默认值:0。参见 fs.copyFileSync()mode 标志。

      ¥mode <integer> modifiers for copy operation. Default: 0. See mode flag of fs.copyFileSync().

    • preserveTimestamps <boolean> 当为 true 时,则 src 的时间戳将被保留。默认值:false

      ¥preserveTimestamps <boolean> When true timestamps from src will be preserved. Default: false.

    • recursive <boolean> 递归复制目录默认:false

      ¥recursive <boolean> copy directories recursively Default: false

    • verbatimSymlinks <boolean> 当为 true 时,则符号链接的路径解析将被跳过。默认值:false

      ¥verbatimSymlinks <boolean> When true, path resolution for symlinks will be skipped. Default: false

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

¥Synchronously copies the entire directory structure from src to dest, including subdirectories and files.

当将目录复制到另一个目录时,不支持 globs,并且行为类似于 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() 不使用回调。

¥fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.

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

更改符号链接的权限。返回 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)#

创建从 existingPathnewPath 的新链接。有关更多详细信息,请参阅 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 <string> | <Buffer> | <URL>

  • options <Object>

    • bigint <boolean> 返回的 <fs.Stats> 对象中的数值是否应为 bigint。默认值:false

      ¥bigint <boolean> Whether the numeric values in the returned <fs.Stats> object should be bigint. Default: false.

    • throwIfNoEntry <boolean> 如果文件系统条目不存在,是否会抛出异常,而不是返回 undefined。默认值:true

      ¥throwIfNoEntry <boolean> Whether an exception will be thrown if no file system entry exists, rather than returning undefined. Default: true.

  • 返回:<fs.Stats>

    ¥Returns: <fs.Stats>

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

  • path <string> | <Buffer> | <URL>

  • options <Object>

    • encoding <string> | <null> 默认值:'utf8'

      ¥encoding <string> | <null> Default: 'utf8'

    • bufferSize <number> 当从目录读取时,在内部缓冲的目录条目数。值越大,性能越好,但内存使用率越高。默认值:32

      ¥bufferSize <number> Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. Default: 32

    • recursive <boolean> 默认值:false

      ¥recursive <boolean> Default: false

  • 返回:<fs.Dir>

    ¥Returns: <fs.Dir>

同步地打开目录。请参阅 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

      ¥maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js retries the operation with a linear backoff wait of retryDelay milliseconds longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true. Default: 0.

    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作将在失败时重试。默认值:false。已弃用。

      ¥recursive <boolean> If true, perform a recursive directory removal. In recursive mode, operations are retried on failure. Default: false. Deprecated.

    • retryDelay <integer> 重试之间等待的时间(以毫秒为单位)。如果 recursive 选项不为 true,则忽略此选项。默认值:100

      ¥retryDelay <integer> The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true. Default: 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 命令的行为,则使用具有选项 { recursive: true, force: true }fs.rmSync()

¥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

      ¥force <boolean> When true, exceptions will be ignored if path does not exist. Default: false.

    • maxRetries <integer> 如果遇到 EBUSYEMFILEENFILEENOTEMPTYEPERM 错误,Node.js 将在每次尝试时以 retryDelay 毫秒的线性退避等待时间重试该操作。此选项表示重试次数。如果 recursive 选项不为 true,则忽略此选项。默认值:0

      ¥maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js will retry the operation with a linear backoff wait of retryDelay milliseconds longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true. Default: 0.

    • recursive <boolean> 如果为 true,则执行递归目录删除。在递归模式下,操作将在失败时重试。默认值:false

      ¥recursive <boolean> If true, perform a recursive directory removal. In recursive mode operations are retried on failure. Default: false.

    • retryDelay <integer> 重试之间等待的时间(以毫秒为单位)。如果 recursive 选项不为 true,则忽略此选项。默认值:100

      ¥retryDelay <integer> The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true. Default: 100.

同步删除文件和目录(以标准 POSIX rm 实用工具为模型)。返回 undefined

¥Synchronously removes files and directories (modeled on the standard POSIX rm utility). Returns undefined.

fs.statSync(path[, options])#

  • path <string> | <Buffer> | <URL>

  • options <Object>

    • bigint <boolean> 返回的 <fs.Stats> 对象中的数值是否应为 bigint。默认值:false

      ¥bigint <boolean> Whether the numeric values in the returned <fs.Stats> object should be bigint. Default: false.

    • throwIfNoEntry <boolean> 如果文件系统条目不存在,是否会抛出异常,而不是返回 undefined。默认值:true

      ¥throwIfNoEntry <boolean> Whether an exception will be thrown if no file system entry exists, rather than returning undefined. Default: true.

  • 返回:<fs.Stats>

    ¥Returns: <fs.Stats>

获取路径的 <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)#

同步取消链接(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.

返回一个 promise,该 promise 将在资源关闭后履行。

¥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>.

返回一个 promise,如果没有更多的目录条目可供读取,则将通过 <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>.

读取完成后,将使用 <fs.Dirent>null(如果读取不到更多的目录条目)调用 callback

¥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.

此外,当在 withFileTypes 选项设置为 true 的情况下调用 fs.readdir()fs.readdirSync() 时,生成的数组将填充 <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>.

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.path#

<fs.Dirent> 对象引用的基本路径。

¥The base path that this <fs.Dirent> object refers to.

类: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> 发生的变更事件的类型

    ¥eventType <string> The type of change event that has occurred

  • filename <string> | <Buffer> 更改的文件名(如果相关/可用)

    ¥filename <string> | <Buffer> The filename that changed (if relevant/available)

当监视的目录或文件中的某些内容发生更改时触发。在 fs.watch() 中查看更多详细信息。

¥Emitted when something changes in a watched directory or file. See more details in fs.watch().

根据操作系统支持,可能不提供 filename 参数。如果提供了 filename,如果 fs.watch() 在其 encoding 选项设置为 'buffer' 的情况下被调用,它将作为 <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.

事件:'error'#

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

调用时,请求只要 <fs.FSWatcher> 处于活动状态,Node.js 事件循环就不会退出。多次调用 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()#

调用时,请求只要 <fs.StatWatcher> 处于活动状态,Node.js 事件循环就不会退出。多次调用 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.ReadStream> 的实例是使用 fs.createReadStream() 函数创建和返回的。

¥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 为后缀的纳秒精度属性。

¥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.

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 版本:

¥bigint version:

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.Stats> 对象是从 fs.lstat() 获得的,则此方法将始终返回 false。这是因为 fs.lstat() 返回有关符号链接本身的信息,而不是它解析到的路径。

¥If the <fs.Stats> object was obtained from fs.lstat(), this method will always 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 Epoch 以来的毫秒数表示。

¥The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch.

stats.mtimeMs#

指示最后一次修改此文件的时间戳,以 POSIX Epoch 以来的毫秒数表示。

¥The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch.

stats.ctimeMs#

指示最后一次更改文件状态的时间戳,以 POSIX Epoch 以来的毫秒数表示。

¥The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch.

stats.birthtimeMs#

指示此文件创建时间的时间戳,以 POSIX Epoch 以来的毫秒数表示。

¥The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch.

stats.atimeNs#

仅在 bigint: true 传入到生成对象的方法中时出现。指示最后一次访问此文件的时间戳,以 POSIX Epoch 以来的纳秒数表示。

¥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 Epoch 以来的纳秒数表示。

¥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 Epoch 以来的纳秒数表示。

¥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 Epoch 以来的纳秒数表示。

¥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 被传递到生成对象的方法中时,属性将是 bigints,否则它们将是 numbers

¥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 属性是 bigints,以纳秒为单位保存相应的时间。它们仅在 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.

atimemtimectimebirthtime 是不同时间的 Date 对象替代表示。Date 和数字值是不关联的。分配新的数值或改变 Date 值不会反映在相应的替代表示中。

¥atime, mtime, ctime, and birthtime are Date object alternate representations of the various times. The Date and number values are not connected. Assigning a new number value, or mutating the Date value, will not be reflected in the corresponding alternate representation.

统计对象中的时间具有以下语义:

¥The times in the stat object have the following semantics:

  • atime "访问时间":上次访问文件数据的时间。由 mknod(2)、utimes(2) 和 read(2) 系统调用更改。

    ¥atime "Access Time": Time when file data last accessed. Changed by the mknod(2), utimes(2), and read(2) system calls.

  • mtime "修改时间":上次修改文件数据的时间。由 mknod(2)、utimes(2) 和 write(2) 系统调用更改。

    ¥mtime "Modified Time": Time when file data last modified. Changed by the mknod(2), utimes(2), and write(2) system calls.

  • ctime "更改时间":上次更改文件状态的时间(inode 数据修改)。由 chmod(2)、chown(2)、link(2)、mknod(2)、rename(2)、unlink(2)、utimes(2)、read(2) 和 write(2) 系统调用更改 。

    ¥ctime "Change Time": Time when file status was last changed (inode data modification). Changed by the chmod(2), chown(2), link(2), mknod(2), rename(2), unlink(2), utimes(2), read(2), and write(2) system calls.

  • birthtime "出生时间":文件创建时间。创建文件时设置一次。在出生时间不可用的文件系统上,此字段可能会保存 ctime1970-01-01T00:00Z(即 Unix 纪元时间戳 0)。在这种情况下,该值可能大于 atimemtime。在 Darwin 和其他 FreeBSD 变体上,如果使用 utimes(2) 系统调用将 atime 显式设置为比当前 birthtime 更早的值,则还要进行设置。

    ¥birthtime "Birth Time": Time of file creation. Set once when the file is created. On file systems where birthtime is not available, this field may instead hold either the ctime or 1970-01-01T00:00Z (ie, Unix epoch timestamp 0). This value may be greater than atime or mtime in this case. On Darwin and other FreeBSD variants, also set if the atime is explicitly set to an earlier value than the current birthtime using the utimes(2) system call.

在 Node.js 0.12 之前,ctime 是 Windows 系统上的 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 版本:

¥bigint version:

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.WriteStream> 的实例是使用 fs.createWriteStream() 函数创建和返回的。

¥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 特定定义不可用。对于可移植应用,建议在使用前检查它们的存在。

¥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 如果存在,复制操作将尝试创建写时复制引用链接。如果底层平台不支持写时复制,则使用回退复制机制。
COPYFILE_FICLONE_FORCE 如果存在,复制操作将尝试创建写时复制引用链接。如果底层平台不支持写时复制,则操作将失败并显示错误。

这些定义在 Windows 上也可用。

¥The definitions are also available on Windows.

文件打开常量#

¥File open constants

以下常量旨在与 fs.open() 一起使用。

¥The following constants are meant for use with fs.open().

常量 描述
O_RDONLY 指示打开文件以进行只读访问的标志。
O_WRONLY 指示打开文件以进行只写访问的标志。
O_RDWR 指示打开文件以进行读写访问的标志。
O_CREAT 如果文件不存在则指示创建文件的标志。
O_EXCL 指示如果设置了 O_CREAT 标志并且文件已存在则打开文件将失败的标志。
O_NOCTTY 标志表示如果路径标识一个终端设备,打开路径不应导致该终端成为进程的控制终端(如果进程还没有一个)。
O_TRUNC 标志表示如果文件存在并且是一个普通文件,并且该文件被成功打开以进行写访问,则其长度应被截断为零。
O_APPEND 指示数据将追加到文件末尾的标志。
O_DIRECTORY 如果路径不是目录,则表示打开应该失败的标志。
O_NOATIME 指示对文件系统的读取访问的标志将不再导致与该文件关联的 atime 信息的更新。该标志仅在 Linux 操作系统上可用。
O_NOFOLLOW 如果路径是符号链接,则表示打开应该失败的标志。
O_SYNC 指示文件为同步 I/O 打开的标志,写操作等待文件完整性。
O_DSYNC 指示文件为同步 I/O 打开的标志,写操作等待数据完整性。
O_SYMLINK 指示打开符号链接本身而不是它指向的资源的标志。
O_DIRECT 设置后,将尝试最小化文件 I/O 的缓存影响。
O_NONBLOCK 指示在可能的情况下以非阻塞模式打开文件的标志。
UV_FS_O_FILEMAP 设置后,将使用内存文件映射来访问文件。此标志仅在 Windows 操作系统上可用。在其他操作系统上,此标志被忽略。

在 Windows 上,只有 O_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.

常量 描述
S_IRWXU 文件模式指示所有者可读、可写和可执行。
S_IRUSR 文件模式指示所有者可读。
S_IWUSR 文件模式指示所有者可写。
S_IXUSR 文件模式指示所有者可执行。
S_IRWXG 文件模式指示群组可读、可写和可执行。
S_IRGRP 文件模式指示群组可读。
S_IWGRP 文件模式指示群组可写。
S_IXGRP 文件模式指示群组可执行。
S_IRWXO 文件模式指示其他人可读、可写和可执行。
S_IROTH 文件模式指示其他人可读。
S_IWOTH 文件模式指示其他人可写。
S_IXOTH 文件模式指示其他人可执行。

在 Windows 上,只有 S_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');

或者,当使用回调 API 时,将 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 始终是绝对路径。

¥file: URLs are always absolute paths.

特定于平台的注意事项#

¥Platform-specific considerations

在 Windows 上,带有主机名的 file: <URL> 转换为 UNC 路径,而带有驱动器号的 file: <URL> 转换为本地绝对路径。file: <URL> 没有主机名也没有盘符会报错:

¥On Windows, file: <URL> with a host name convert to UNC paths, while file: <URL> with drive letters convert to local absolute paths. file: <URL> 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> with drive letters must use : as a separator just after the drive letter. Using another separator will result in an error.

在所有其他平台上,不支持具有主机名的 file: <URL> 并将导致错误:

¥On all other platforms, file: <URL> 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> 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':打开文件进行追加。如果文件不存在,则创建该文件。

    ¥'a': Open file for appending. The file is created if it does not exist.

  • 'ax':类似于 'a' 但如果路径存在则失败。

    ¥'ax': Like 'a' but fails if the path exists.

  • 'a+':打开文件进行读取和追加。如果文件不存在,则创建该文件。

    ¥'a+': Open file for reading and appending. The file is created if it does not exist.

  • 'ax+':类似于 'a+' 但如果路径存在则失败。

    ¥'ax+': Like 'a+' but fails if the path exists.

  • 'as':以同步模式打开文件进行追加。如果文件不存在,则创建该文件。

    ¥'as': Open file for appending in synchronous mode. The file is created if it does not exist.

  • 'as+':以同步模式打开文件进行读取和追加。如果文件不存在,则创建该文件。

    ¥'as+': Open file for reading and appending in synchronous mode. The file is created if it does not exist.

  • 'r':打开文件进行读取。如果文件不存在,则会发生异常。

    ¥'r': Open file for reading. An exception occurs if the file does not exist.

  • 'rs':打开文件以同步模式读取。如果文件不存在,则会发生异常。

    ¥'rs': Open file for reading in synchronous mode. An exception occurs if the file does not exist.

  • 'r+':打开文件进行读写。如果文件不存在,则会发生异常。

    ¥'r+': Open file for reading and writing. An exception occurs if the file does not exist.

  • 'rs+':以同步模式打开文件进行读写。指示操作系统绕过本地文件系统缓存。

    ¥'rs+': Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.

    这主要用于在 NFS 挂载上打开文件,因为它允许跳过可能过时的本地缓存。它对 I/O 性能有非常实际的影响,因此除非需要,否则不建议使用此标志。

    ¥This is primarily useful for opening files on NFS mounts as it allows skipping the potentially stale local cache. It has a very real impact on I/O performance so using this flag is not recommended unless it is needed.

    这不会将 fs.open()fsPromises.open() 变成同步阻塞调用。如果需要同步操作,应该使用类似 fs.openSync() 的东西。

    ¥This doesn't turn fs.open() or fsPromises.open() into a synchronous blocking call. If synchronous operation is desired, something like fs.openSync() should be used.

  • 'w':打开文件进行写入。创建(如果它不存在)或截断(如果它存在)该文件。

    ¥'w': Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

  • 'wx':类似于 'w' 但如果路径存在则失败。

    ¥'wx': Like 'w' but fails if the path exists.

  • 'w+':打开文件进行读写。创建(如果它不存在)或截断(如果它存在)该文件。

    ¥'w+': Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

  • 'wx+':类似于 'w+' 但如果路径存在则失败。

    ¥'wx+': Like 'w+' but fails if the path exists.

flag 也可以是 open(2) 记录的数字;常用常量可从 fs.constants 获得。在 Windows 上,标志会在适用的情况下转换为等效的标志,例如 O_WRONLYFILE_GENERIC_WRITE,或 O_EXCL|O_CREATCREATE_NEW,为 CreateFileW 所接受。

¥flag can also be a number as documented by open(2); commonly used constants are available from fs.constants. On Windows, flags are translated to their equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE, or O_EXCL|O_CREAT to CREATE_NEW, as accepted by 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.