To change permission on a file asynchronously, you can use the chmod()
function from the fs
(filesystem) module in Node.js.
Let's say I have a file called myFile.txt
and want to change the permission to 775
. Here you can use the fs.chmod()
asynchronous method and pass:
- a path to the file as the first argument
- the mode or permissions to allow as the second argument such as the
775
. The permission can either be an octal number or a string. My choice is to go with the octal number as it is easy to understand. Also, make sure to prefix the775
with0o
which is the convention to write the octal number in Node.js and many other programming languages. To understand what the number775
means click here - and a callback function as the third argument which will get invoked when the permissions are changed for that file. The callback function will receive an
error
as the argument if any.
It can be done like this,
// require fs (filesystem) module
const fs = require("fs");
// change permission of myFile.txt to 775
fs.chmod("myFile.txt", 0o775, (error) => {
// in-case of any errors
if (error) {
console.log(error);
return;
}
// do other stuff
console.log("Permissions are changed for the file!");
});
See the above code live in repl.it
That's it 😃.
Understand what the 775
octal number means?
You may be wondering what is 775
, it can be summarised like this:
- the first value
7
means to giveread
,write
andexecute
permission to the owner of the file. - the second value
7
means to giveread
,write
andexecute
permissions for the group. - the third value
5
means to give onlyread
andexecute
permission for others.
So to put it simply the leftmost value is where we define the permission for the owner
, then the permission for the group
, and the permission for others
.
FULL LIST OF PERMISSION VALUES
7
- read, write, and execute6
- read and write5
- read and execute4
- read only3
- write and execute2
- write only1
- execute only0
- no permission