Check Permissions of a File or Directory

suggest change

fs.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:

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);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents