What's the most portable way to check if a directory is writable in nodejs?

A friend asked me this question, and I gave de facto two options.

First of all, checking file permissions:

//adapted from https://stackoverflow.com/questions/11775884/nodejs-file-permissions#answer-11781404
var fs = require('fs')

function canWrite(directory) {
 var stat = fs.statSync(directory)

 // 2 is the octal value for chmod -w-
 return !!( 2 & (stat.mode & parseInt('777', 8)).toString(8)[0] ) //first char is the owner
}

      

What if user ( process.uid

) was not the owner of the filesystem ( stat.uid

) nor in group ( process.gid vs stat.gid

)? He will still get permission 644

and recording will be impossible.

How can we know (with nodejs) that the current user belongs to the filesystem group ( stat.gid

)? Easy in bash , but for portability it would be a mess with nodejs.

Second way, lazy:

var fs = require('fs')
var canWrite = true

try {
  fs.writeFileSync('./test')
  fs.unlinkSync('./test')
} catch(e) {
  canWrite = false
}

if(canWrite) {
 //go for it
}

      

Lazy couse solution, but it should do the job. It can also block the kernel buffer. On the other hand, it is fs.Stat

usually cached by operating systems.

None of these solutions are perfect.

What would you do? Is there something I am missing?

+3


source to share


1 answer


What about:

var fs = require('fs');

fs.access(__dirname, fs.constants.W_OK, function(err) {
  if(err){
    console.error("can't write");
    process.exit(1);
  }

  console.log("can write");
  process.exit(0);
});

      

Documents here



fs.constants.W_OK

: the file can be written by calling ...

If you run the above with sudo

, you may get different outputs depending on the user's rights.

+8


source







All Articles