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
- The user
Royhas the user-id (or
- and the id of the group (or
gid) to set ownership is
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!");
fs.chownSync() synchronous method accepts 3 arguments:
- The first one is the
pathto 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.