fsPromises.access(path[, mode])
path<string> | <Buffer> | <URL>mode<integer> 默认值:fs.constants.F_OK- 返回:<Promise> 成功时返回
undefined。
测试用户对由 path 指定的文件或目录的权限。
mode 参数是一个可选的整数,用于指定要执行的可访问性检查。mode 应为 fs.constants.F_OK 的值,或由 fs.constants.R_OK、fs.constants.W_OK 和 fs.constants.X_OK 中任意组合按位或计算得到的掩码(例如 fs.constants.W_OK | fs.constants.R_OK)。请查看 文件访问常量 以了解 mode 的可能取值。
【Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OK
or a mask consisting of the bitwise OR of any of fs.constants.R_OK,
fs.constants.W_OK, and fs.constants.X_OK (e.g.
fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.】
如果可访问性检查成功,Promise 将以无值的形式被实现。如果任何可访问性检查失败,Promise 将被一个 <Error> 对象拒绝。以下示例检查当前进程是否可以读取和写入文件 /etc/passwd。
【If the accessibility check is successful, the promise is fulfilled with no
value. If any of the accessibility checks fail, the promise is rejected
with an <Error> object. The following example checks if the file
/etc/passwd can be read and written by the current process.】
import { access, constants } from 'node:fs/promises';
try {
await access('/etc/passwd', constants.R_OK | constants.W_OK);
console.log('can access');
} catch {
console.error('cannot access');
} 在调用 fsPromises.open() 之前使用 fsPromises.access() 来检查文件的可访问性是不推荐的。这会引入竞争条件,因为在两次调用之间,其他进程可能会改变文件的状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不可访问时产生的错误。
【Using fsPromises.access() to check for the accessibility of a file before
calling fsPromises.open() is not recommended. Doing so introduces a race
condition, since other processes may change the file's state between the two
calls. Instead, user code should open/read/write the file directly and handle
the error raised if the file is not accessible.】