Due to the modules my node program uses, it requires root to run. This is because it has to run a HTTP server on port 80 (and as you know, lower ports like that require root in order to be used).
But, this program also uses a fs
method to create a file. I don't mind if root is the owner as long as I can change the permissions... But that's exactly where I'm hitting the bump.
I'm using the fs.mkdir
function to create a directory like so:
(Lets say this file is named create.js
)
fs.mkdir(__dirname + "/.loud", 0777, function(err){
if (err) console.log("Failed to create file at " + __dirname + "/.loud");
});
When executing it (Remember, via sudo, sudo node create.js
) it does in fact create the folder... But the permissions provided (0777
) are wrong!...
If I'm not mistaken, 7
implies read, write, and execute. Using it for the 3 fields (777
+ a leading 0
to represent it as an octal) should imply that everyone can read, write, and execute inside this folder... But here is what I get when checking the folder's permissions:
[imac] jamen : ~/Tests/mkdir $ ls -a -l .
...
drwxr-xr-x 2 root root 4096 Jun 12 22:27 .loud
So, lets seperate the beginning permissions part:
d, rwx, r-x, r-x
So, I don't know what the d
means (feel free to tell me in the comments), so I think we can throw that out. Here is what the other means:
- The owner can read, write, and execute (as expected)
- The group can read, and execute (What?! We specified
7
, meaning it should also be able to write???) - Everyone else can read, and execute (Again... We also specified
7
, should everyone also be able to write?)
So, in attempt to solve, I went on a venture and found this post on SE.Unix, and after reading it, I thought I might as well try to specify the permissions in decimal format, instead of octal format...
Here is how I changed our create.js
file:
fs.mkdir(__dirname + "/.loud", 511, function(err){
if (err) console.log("Failed to create file at " + __dirname + "/.loud");
});
(Since 0777 in octal is represented as 511 in decimal)
But, this unfortunately gives the same exact results (yes, I did delete the folder before running this again, otherwise NodeJS would have passed an error in the callback):
[imac] jamen : ~/Tests/mkdir $ ls -a -l .
...
drwxr-xr-x 2 root root 4096 Jun 12 22:35 .loud
Am I misunderstanding something about Unix's permissions scheme, or am I making a mistake in NodeJS?
How would I fix this so the folder gets the permissions 0777
, implying the owner as rwx permissoins, the group has rwx permissoins, and everyone else has rwx permissions...?
Because it applies umask on your mode. Type
umask
in your console, you will see 022 or 0022.You can overwrite it for your node process with
process.umask(newmask);