文件系统标志


【File system flags】

以下标志可在任何接受字符串的 flag 选项中使用。

【The following flags are available wherever the flag option takes a string.】

  • 'a':以追加模式打开文件。如果文件不存在,则会创建该文件。

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

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

  • 'ax+':类似 'a+',但如果路径已存在则操作失败。

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

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

  • 'r':以只读模式打开文件。如果文件不存在,将会发生异常。

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

  • 'r+':以读写模式打开文件。如果文件不存在,将发生异常。

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

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

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

  • 'w':以写入模式打开文件。如果文件不存在则创建文件,如果文件已存在则清空文件内容。

  • 'wx':类似 'w',但如果路径已存在则操作失败。

  • 'w+':打开文件进行读写。如果文件不存在,将创建文件;如果文件存在,将清空文件内容。

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

flag 也可以是一个数字,如 open(2) 文档中所述;常用的常量可以从 fs.constants 获取。在 Windows 上,标志会被转换为相应的等效值,例如将 O_WRONLY 转换为 FILE_GENERIC_WRITE,或者将 O_EXCL|O_CREAT 转换为 CREATE_NEW,这些都是 CreateFileW 可接受的。

排他标志 'x'(open(2) 中的 O_EXCL 标志)会导致如果路径已存在,则操作返回错误。在 POSIX 系统上,如果路径是符号链接,即使链接指向一个不存在的路径,使用 O_EXCL 也会返回错误。排他标志在网络文件系统上可能无法正常工作。

【The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to return an error if the path already exists. On POSIX, if the path is a symbolic link, using O_EXCL returns an error even if the link is to a path that does not exist. The exclusive flag might not work with network file systems.】

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

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

修改文件而不是替换它可能需要将 flag 选项设置为 'r+' 而不是默认的 'w'

【Modifying a file rather than replacing it may require the flag option to be set to 'r+' rather than the default 'w'.】

某些标志的行为是平台特定的。因此,在 macOS 和 Linux 上使用 'a+' 标志打开目录,如下面的例子所示,将会返回错误。相比之下,在 Windows 和 FreeBSD 上,会返回一个文件描述符或 FileHandle

【The behavior of some flags are platform-specific. As such, opening a directory on macOS and Linux with the 'a+' flag, as in the example below, will return an error. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle will be returned.】

// macOS and Linux
fs.open('<directory>', 'a+', (err, fd) => {
  // => [Error: EISDIR: illegal operation on a directory, open <directory>]
});

// Windows and FreeBSD
fs.open('<directory>', 'a+', (err, fd) => {
  // => null, <fd>
}); 

在 Windows 上,使用 'w' 标志(通过 fs.open()fs.writeFile()fsPromises.open())打开已存在的隐藏文件会失败,并返回 EPERM。可以使用 'r+' 标志打开已存在的隐藏文件进行写入。

【On Windows, opening an existing hidden file using the 'w' flag (either through fs.open(), fs.writeFile(), or fsPromises.open()) will fail with EPERM. Existing hidden files can be opened for writing with the 'r+' flag.】

可以调用 fs.ftruncate()filehandle.truncate() 来重置文件内容。

【A call to fs.ftruncate() or filehandle.truncate() can be used to reset the file contents.】