How to change the permissions of a file synchronously using Node.js?
Published March 30, 2021
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 the
0owhich is the convention to write the octal number in Node.js and many other programming languages. To understand what the number
775means 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
7means to give
executepermission to the owner of the file.
- the second value
7means to give
executepermissions for the group.
- the third value
5means to give only
executepermission 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
FULL LIST OF PERMISSION VALUES
7- read, write, and execute
6- read and write
5- read and execute
4- read only
3- write and execute
2- write only
1- execute only
0- no permission