Skip to content
Related Articles

Related Articles

Node.js | fs.chownSync() Method
  • Last Updated : 08 May, 2020

The fs.chownSync() method is used to synchronously change the owner and group of the given path. 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.chownSync( path, uid, gid )

Parameters: This method accepts three parameters as mentioned above and described below:

  • path: It is a string, Buffer or URL that denotes the path 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.chownSync() method in Node.js:

Example 1: This example shows the setting of the owner.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the
// fs.chownSync() method
  
// Import the filesystem module
const fs = require('fs');
  
let filepath = "example_file.txt";
  
// Set the owner to a new one keeping the group same
// New owner is "geeksforgeeks" with user id 1100
// The old group is "xubuntu" with group id 999
fs.chownSync(filepath, 1100, 999);
console.log("Given uid and gid set successfully");

chevron_right


Before Running the Code:

xubuntu@xubuntu: ~/Desktop/fs-chownSync$ ls -l
total 8
-rw-rw--w- 1 xubuntu xubuntu 4 Apr 23 09:08 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 23 09:08 index.js

Output of the Code:

Given uid and gid set successfully

After Running the Code:

xubuntu@xubuntu: ~/Desktop/fs-chownSync$ ls -l
total 8
-rw-rw--w- 1 geeksforgeeks xubuntu 4 Apr 23 09:08 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 23 09:08 index.js

Example 2: This example shows the setting of the group.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the
// fs.chownSync() method
  
// Import the filesystem module
const fs = require('fs');
  
let filepath = "example_file.txt";
  
// Set the group to a new one keeping the owner same
// New group is "editor" with group id 1201
fs.chownSync(filepath, 999, 1201);
console.log("Given uid and gid set successfully");

chevron_right


Before Running the Code:

xubuntu@xubuntu: ~/Desktop/fs-chownSync$ ls -l
total 8
-rw-rw--w- 1 xubuntu xubuntu 4 Apr 23 09:08 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 23 09:08 index.js

Output of the Code:

Given uid and gid set successfully

After Running the Code:

xubuntu@xubuntu: ~/Desktop/fs-chownSync$ ls -l
total 8
-rw-rw--w- 1 xubuntu editor 4 Apr 23 09:08 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 23 09:08 index.js

Reference: https://nodejs.org/api/fs.html#fs_fs_chownsync_path_uid_gid

My Personal Notes arrow_drop_up
Recommended Articles
Page :