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
Royhas the user-id (oruid) of512 - and the id of the group (or
gid) to set ownership is1000.
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
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.