Open In App

Node.js fs.chown() Method

The fs.chown() method is used to asynchronously 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 has a callback function which returns any error that may occur if the function fails.

Syntax:



fs.chown( path, uid, gid, callback )

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

Below examples illustrate the fs.chown() method in Node.js:



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




// Node.js program to demonstrate the
// fs.chown() 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 1541
fs.chown(filepath, 1541, 999, (error) => {
  if (error)
    console.log("Error Code:", error);
  else
    console.log("uid and gid set successfully");
});

Before Running the Code:

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

Output of the Code:

Given uid and gid set successfully

After Running the Code:

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

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




// Node.js program to demonstrate the
// fs.chown() method
  
// Import the filesystem module
const fs = require('fs');
  
let filepath = "example_file.txt";
  
// Set the owner and group both to a new one
// New owner is "sam" with owner id 1500
// New group is "author" with group id 1021
fs.chown(filepath, 1500, 1021, (error) => {
  if (error)
    console.log("Error Code:", error);
  else
    console.log("uid and gid set successfully");
});

Before Running the Code:

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

Output of the Code:

Given uid and gid set successfully

After Running the Code:

xubuntu@xubuntu: ~/Desktop/fs-chown$ ls -l
total 8
-rw-rw--w- 1 sam author 4 Apr 25 04:09 example_file.txt
-rw-rw-r-- 1 xubuntu xubuntu 290 Apr 25 04:09 index.js

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


Article Tags :