a blog for those who code

Wednesday, 29 October 2014

Alter File Permissions in Nodejs

In this post we will show you how to alter file permissions in Nodejs. When you are planning to alter the permissions on a file, you might want to change the ownership. In Nodejs we use fs.chown to change the ownership of a file.

According to Nodejs fs.chown function accepts four arguments that are path, uid, gid, callback.

path : file you wish to perform the ownership alteration
uid : integer of the user id on your system
gid : integer of the group id to which the user belongs
callback : callback function attached with fs.chown

To determine the User and Group Id Numbers you have to use below commands in Terminal

> id -u Your_UserName
> id -g Your_UserName

To Change access mode of the file you can use fs.chmod whioch accepts three arguments that are path, mode, callback.

path : file you wish to perform the access mode alteration
mode : The integer value of the octal permission code
callback : callback function attached with fs.chmod

File Access Settings of various files are :

4000 : Hidden File
2000 : System File
1000 : Archive bit
0400 : Individual read
0200 : Individual write
0100 : Individual execute
0040 : Group read
0020 : Group write
0010 : Group execute
0004 : Other read
0002 : Other write
0001 : Other execute

Where 1 represents execute, 2 represents write and 4 represents read

Code :

var fs = require('fs');
var file = 'D:\example\example1.js';
//Hide File
fs.chmod(file, 4000, function(err)){
if(err) throw err;
});
//Individual Write On File
fs.chmod(file, 0200, function(err)){
if(err) throw err;
});
//Individual write + execute
fs.chmod(file, 0300, function(err)){
if(err) throw err;
});
//Individual read + write + execute (full access to an individual)
fs.chmod(file, 0700, function(err)){
if(err) throw err;
});
//Change Owner by root user
fs.chown(file, 0, 0, function(err)){
if(err) throw err;
});

Please Like and Share Codingdefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License