Nodejs File Permissions

早过忘川 提交于 2019-11-27 02:08:20

问题


In Node the fs.stat method returns an fs.Stats object right, and I can get the file permission through the fs.Stats.mode property.

Here is a real output from both node and shell for the same directories:

node  shell
17407 d rwx rwx rwt
16877 d rwx r-x r-x
16749 d r-x r-x r-x
16832 d rwx --- ---

I need to know how to parse the fs.Stats.mode number to get the permissions.

Answer

The number is in octal numeric system, after converting to decimal looks like this:

17407 41777 d rwx rwx rwt
16877 40755 d rwx r-x r-x
16749 40555 d r-x r-x r-x
16832 40777 d rwx --- ---

And the convertion from octal to decimal system is like this:

parseInt(stat.mode.toString(8), 10)

Great tutorial on file permissions in linux - https://www.linux.com/learn/understanding-linux-file-permissions


回答1:


var checkPermission = function (file, mask, cb){
    fs.stat (file, function (error, stats){
        if (error){
            cb (error, false);
        }else{
            cb (null, !!(mask & parseInt ((stats.mode & parseInt ("777", 8)).toString (8)[0])));
        }
    });
};

canExecute():

checkPermission (<path>, 1, cb);

canRead():

checkPermission (<path>, 4, cb);

canWrite():

checkPermission (<path>, 2, cb);



回答2:


The number format is platform dependent, so you can't, reliably.

When NodeJs starts exposing the underlying S_ISDIR function and the S_IRUSR and similar constants, you can.

Some information on the stat format: http://linux.die.net/man/2/stat



来源:https://stackoverflow.com/questions/11775884/nodejs-file-permissions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!