Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

node.js - Nodejs File Permissions

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...