Check Permissions of a File or Directory
suggest changefs.access() checks whether a path exists and whether the process has the requested permissions. It does not return a result. If the callback receives no error, the path exists and the requested permissions are present. An error can mean the path is missing or the permission is denied.
The modes live on fs.constants:
fs.constants.F_OK- the path is visible to the process (existence only; this is the default when no mode is given)fs.constants.R_OK- Has read permissionsfs.constants.W_OK- Has write permissionsfs.constants.X_OK- Has execute permissions (Works the same asfs.constants.F_OKon Windows)
Asynchronously
var fs = require('fs');
var path = '/path/to/check';
// checks execute permission
fs.access(path, fs.constants.X_OK, (err) => {
if (err) {
console.log('cannot access %s', path);
} else {
console.log('can execute %s', path);
}
});
// Check if we have read/write permissions
// When specifying multiple permission modes
// each mode is separated by a pipe : `|`
fs.access(path, fs.constants.R_OK | fs.constants.W_OK, (err) => {
if (err) {
console.log('cannot access %s', path);
} else {
console.log('can read/write %s', path);
}
});
Synchronously
fs.access also has a synchronous version fs.accessSync. When using fs.accessSync you must enclose it within a try/catch block.
// Check write permission
try {
fs.accessSync(path, fs.constants.W_OK);
console.log('can write %s', path);
}
catch (err) {
console.log('cannot access %s', path);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents