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

Published April 7, 2021

To change the ownership of a file synchronously, you can use the chownSync() 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.chownSync("./myFile.txt", 512, 1000);

// Success message
console.log("Ownership of file has changed!");

The fs.chownSync() synchronous method accepts 3 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.

See the above code live in repl.it.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter