Node.js fs.accessSync() 方法
fs.accessSync() 方法用于同步测试给定文件或目录的权限。可以使用文件访问常量将要检查的权限指定为参数。也可以通过使用按位 OR运算符创建具有多个文件常量的掩码来检查多个文件权限。
句法:
fs.accessSync( path, mode )
参数:此方法接受上面提到的两个参数,如下所述:
- path:它是一个String,Buffer或URL,表示必须对其进行权限测试的文件或目录的路径。
- mode:它是一个整数值,表示要测试的权限。逻辑 OR运算符可用于分隔多个权限。它可以具有值
fs.constants.F_OK
、fs.constants.R_OK
、fs.constants.W_OK
和fs.constants.X_OK
。它是一个可选参数。默认值为fs.constants.F_OK
。
下面的示例说明了 Node.js 中的fs.accessSync() 方法:
例1:本例展示了一个文件读写权限的测试。
// Node.js program to demonstrate the
// fs.accessSync() method
// Import the filesystem module
const fs = require('fs');
// Allowing only read permission
console.log("Giving only read permission to user");
fs.chmodSync("example.txt", fs.constants.S_IRUSR);
// Test the read permission
console.log('\n> Checking Permission for reading the file');
try {
fs.accessSync('example.txt', fs.constants.R_OK);
console.log('File can be read');
} catch (err) {
console.error('No Read access');
}
// Test both the read and write permission
console.log('\n> Checking Permission for reading and writing to file');
try {
fs.accessSync('example.txt', fs.constants.R_OK | fs.constants.W_OK);
console.log('File can be read and written');
} catch (err) {
console.error('No Read and Write access');
}
输出:
Giving only read permission to user
> Checking Permission for reading the file
File can be read
> Checking Permission for reading and writing to file
No Read and Write access
示例 2:此示例显示了对文件是否存在的测试。
// Node.js program to demonstrate the
// fs.accessSync() method
// Import the filesystem module
const fs = require('fs');
// Test the if the file exists
console.log('\n> Checking if the file exists');
try {
fs.accessSync('example.txt', fs.constants.F_OK);
console.log('File does exist');
} catch (err) {
console.error('File does not exist');
}
console.log('\nCreating the file');
fs.writeFileSync("example.txt", "Test File");
// Test the if the file exists again
console.log('\n> Checking if the file exists');
try {
fs.accessSync('example.txt', fs.constants.F_OK);
console.log('File does exist');
} catch (err) {
console.error('File does not exist');
}
输出:
> Checking if the file exists
File does not exist
Creating the file
> Checking if the file exists
File does exist
参考: https://nodejs.org/api/fs.html#fs_fs_accesssync_path_mode