fsPromises.access(path[, mode])


测试用户对 path 指定的文件或目录的权限。 mode 参数是可选的整数,指定要执行的可访问性检查。 查看文件访问的常量以获取可能的 mode 值。 可以创建由两个或多个值的按位或组成的掩码(例如 fs.constants.W_OK | fs.constants.R_OK)。

如果可访问性检查成功,则不带值解决 promise。 如果任何可访问性检查失败,则使用 <Error> 对象拒绝 promise。 以下示例检查当前进程是否可以读写文件 /etc/passwd

import { access } from 'fs/promises';
import { constants } from 'fs';

try {
  await access('/etc/passwd', constants.R_OK | constants.W_OK);
  console.log('can access');
} catch {
  console.error('cannot access');
}

不建议在调用 fsPromises.open() 之前使用 fsPromises.access() 检查文件的可访问性。 这样做会引入竞争条件,因为其他进程可能会在两次调用之间更改文件的状态。 而是,用户代码应直接打开/读取/写入文件,并处理无法访问文件时引发的错误。

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. Check File access constants for possible values of mode. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

If the accessibility check is successful, the promise is resolved 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 } from 'fs/promises';
import { constants } from 'fs';

try {
  await access('/etc/passwd', constants.R_OK | constants.W_OK);
  console.log('can access');
} catch {
  console.error('cannot 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.