The fsPromises.access() method is used to test the permissions of a given file or directory specified by path. The permissions to be checked can be specified as a parameter using file access constants. It is also possible to check multiple file permissions by using the bitwise OR operator to create a mask with more than one file constant.
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.
fsPromises.access( path, mode )
Parameters: This method accepts two parameters as mentioned above and described below:
- path: It is a String, Buffer or URL that denotes the path of the file or directory for which the permission has to be tested.
- mode: It is an integer value that denotes the permission to be tested for. The logical OR operator can be used to separate multiple permission. It can have the values fs.constants.F_OK, fs.constants.R_OK, fs.constants.W_OK and fs.constants.X_OK. It is an optional parameter. The default value is fs.constants.F_OK.
Return Value: It returns the Promise.
Example 1: This example shows the testing of the write permission of the file.
Can not be accessed
Example 2: This example shows the testing of the read and write permission of a file.
Giving only read permission to the user Can be accessed Can not be accessed
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.