How to change the permissions of a file asynchronously using Node.js?

March 29, 2021 - 2 min read

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 the 775 with 0o which is the convention to write the octal number in Node.js and many other programming languages. To understand what the number 775 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 give read, write and execute permission to the owner of the file.
  • the second value 7 means to give read, write and execute permissions for the group.
  • the third value 5 means to give only read and execute 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 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

Feel free to share if you found this useful 😃.