To change permission on a file synchronously, you can use the chmodSync()
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.chmodSync()
synchronous 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
It can be done like this,
// require fs (filesystem) module
const fs = require("fs");
// change permission of myFile.txt to 775
fs.chmodSync("myFile.txt", 0o775);
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