How to change the ownership of the file asynchronously in Node.js?

April 6, 2021 - 2 min read

To change the ownership of a file asynchronously, you can use the chown() method from the fs (filesystem) module in Node.js.

Let's say I have a file called myFile.txt and want to change the owner from me to another user called Roy.

For example,

  • The user Roy has the user-id (or uid) of 512
  • and the id of the group (or gid) to set ownership is 1000.

So it can be done like this,

// require fs module
const fs = require("fs");

// Change ownership of file
fs.chown("./myFile.txt", 512, 1000, (error) => {
  // in case of any error
  if (error) {
    console.log(error);
    return;
  }

  // otherwise show success message that ownership is changed
  console.log("Ownership of file has changed!");
});

The fs.chown() asynchronous method accepts 4 arguments:

  • The first one is the path to the file.
  • The second one is the user-id (or uid) of the user that needs to have ownership of the file.
  • The third one is the group-id (or gid) that needs to have ownership of the file.
  • The fourth argument is an error first callback function which will get executed after successfully changing the ownership of the file.

See the above code live in repl.it.

Feel free to share if you found this useful 😃.