Open In App

Node.js | fs. fchownSync() Method

Last Updated : 08 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
The fs.fchownSync() method is used to synchronously change the owner and group of the given file descriptor. The function accepts a user id and group id that can be used to set the respective owner and group. It does not return anything. Syntax:
fs.fchownSync( fd, uid, gid )
Parameters: This method accepts three parameters as mentioned above and described below:
  • fd: It is an integer that denotes the file descriptor of the file of which the owner and group has to be changed.
  • uid: It is a number that denotes the user id that corresponds to the owner to be set.
  • gid: It is a number that denotes the group id that corresponds to the group to be set.
Below examples illustrate the fs.fchownSync() method in Node.js: Example 1: This example shows the setting of the owner. javascript
// Node.js program to demonstrate the
// fs.fchownSync() method

// Import the filesystem module
const fs = require('fs');

// Get the file descriptor for the file
let fd = fs.openSync("example_file.txt", "r");

// Set the owner to a new one keeping the group same
// New owner is "geeksforgeeks" with user id 1010
// The old group is "xubuntu" with group id 999
fs.fchownSync(fd, 1010, 999);
console.log("uid and gid set successfully");
Before Running the Code:
xubuntu@xubuntu: ~/Desktop/fs-fchownSync$ ls -l
total 8
-rw-rw--w- 1 xubuntu xubuntu 4 Apr 22 09:10 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 22 09:15 index.js
Output of the Code:
Given uid and gid set successfully
After Running the Code:
xubuntu@xubuntu: ~/Desktop/fs-fchownSync$ ls -l
total 8
-rw-rw--w- 1 geeksforgeeks xubuntu 4 Apr 22 09:10 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 22 09:15 index.js
Example 2: This example shows the setting of the group. javascript
// Node.js program to demonstrate the
// fs.fchownSync() method

// Import the filesystem module
const fs = require('fs');

// Get the file descriptor for the file
let fd = fs.openSync("example_file.txt", "r");

// Set the group to a new one keeping the owner same
// The old owner is "xubuntu" with user id 999
// New group is "author" with group id 1015
fs.fchownSync(fd, 999, 1015);
console.log("uid and gid set successfully");
Before Running the Code:
xubuntu@xubuntu: ~/Desktop/fs-fchownSync$ ls -l
total 8
-rw-rw--w- 1 xubuntu xubuntu 4 Apr 22 09:10 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 22 09:15 index.js
Output of the Code:
Given uid and gid set successfully
After Running the Code:
xubuntu@xubuntu: ~/Desktop/fs-fchownSync$ ls -l
total 8
-rw-rw--w- 1 xubuntu author 4 Apr 22 09:10 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 22 09:15 index.js
Reference: https://nodejs.org/api/fs.html#fs_fs_fchownsync_fd_uid_gid

Similar Reads