← 中文资源

简体中文版本

fs.access 检查路径权限

用 fs.access 配合 F_OK、R_OK、W_OK 常量探测存在性与读写权限:路径缺失时以 ENOENT 拒绝,而不是同步抛错。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

exists: config.json
readable and writable: config.json
missing.json rejected: true

实现说明

异步流被 await 线性化,失败处理保持局部。node:fs/promises 提供 writeFile、access、constants——内建表面,不涉及任何包。

使用要点

  • node:fs/promises 是 Node.js 内建模块——随运行时自带,无需安装。
  • 跑完文件,输出里会留下标记——exists: config.json、readable and writable: config.json、missing.json rejected:。

常见问题

有第三方依赖吗?

不需要。导入解析到 Node.js 核心模块,运行时自带。

核心语句

await access('config.json', constants.R_OK | constants.W_OK);
await access('missing.json', constants.F_OK);
await access('config.json', constants.F_OK);

代码示例

import { writeFile, access, constants } from 'node:fs/promises';

await writeFile('config.json', '{}');

// access resolves when the path passes the requested checks
await access('config.json', constants.F_OK);
console.log('exists: config.json');

// R_OK / W_OK / X_OK test read, write and execute permission
await access('config.json', constants.R_OK | constants.W_OK);
console.log('readable and writable: config.json');

// a missing path rejects with ENOENT instead of throwing synchronously
try {
  await access('missing.json', constants.F_OK);
} catch (err) {
  console.log('missing.json rejected:', err.code === 'ENOENT');
}