Search code examples
filenode.jspermissions

How to test file permissions using node.js?


How can I check to see the permissions (read/write/execute) that a running node.js process has on a given file?

I was hoping that the fs.Stats object had some information about permissions but I don't see any. Is there some built-in function that will allow me to do such checks? For example:

var filename = '/path/to/some/file';
if (fs.canRead(filename)) // OK...
if (fs.canWrite(filename)) // OK...
if (fs.canExecute(filename)) // OK...

Surely I don't have to attempt to open the file in each of those modes and handle an error as the negative affirmation, right? There's got to be a simpler way...


Solution

  • I am late, but, I was looking for same reasons as yours and learnt about this.

    fs.access is the one you need. It is available from node v0.11.15.

    function canWrite(path, callback) {
      fs.access(path, fs.W_OK, function(err) {
        callback(null, !err);
      });
    }
    
    canWrite('/some/file/or/folder', function(err, isWritable) {
      console.log(isWritable); // true or false
    });