Nodejs文件权限

sim*_*imo 20 file-permissions file node.js

在Node中,该fs.stat方法返回一个fs.Stats对象,我可以通过该fs.Stats.mode属性获取文件权限.

以下是来自节点和shell的相同目录的实际输出:

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 --- ---
Run Code Online (Sandbox Code Playgroud)

我需要知道如何解析fs.Stats.mode数字以获得权限.

回答

数字是八进制数字系统,转换为十进制后如下所示:

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 --- ---
Run Code Online (Sandbox Code Playgroud)

从八进制到十进制的转换是这样的:

parseInt(stat.mode.toString(8), 10)
Run Code Online (Sandbox Code Playgroud)

关于linux中文件权限的精彩教程 - https://www.linux.com/learn/understanding-linux-file-permissions

Gab*_*mas 21

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])));
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

canExecute():

checkPermission (<path>, 1, cb);
Run Code Online (Sandbox Code Playgroud)

canRead():

checkPermission (<path>, 4, cb);
Run Code Online (Sandbox Code Playgroud)

canWrite():

checkPermission (<path>, 2, cb);
Run Code Online (Sandbox Code Playgroud)


Dee*_*tan 1

数字格式取决于平台,因此您不能可靠地进行。

当 NodeJs 开始公开底层S_ISDIR函数和S_IRUSR类似的常量时,您就可以了。

有关 stat 格式的一些信息:http://linux.die.net/man/2/stat