Nodejs文件权限 [英] Nodejs File Permissions

查看:361
本文介绍了Nodejs文件权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 --- ---

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

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

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

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)

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

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

推荐答案

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);

这篇关于Nodejs文件权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆