Diving Into Node’s filehandle.chown()

Sean Prashad
Open Source @ Seneca

--

Changing file ownership in Unix file systems

The Node API states that this function is responsible for…

Changing the ownership of the file then resolving the Promise with no arguments upon success.

What does that mean exactly? Let’s investigate some more.

Background

Chown(), an abbreviation for “change owner”, arises from Unix-like operating systems and the need to change file and directory ownership within the file system. This is not to be confused with chmod(), which stands for “change mode”, which allows the permissions of files and folders in Unix to be changed.

Basically who owns the file/folder vs. do we have read/write permission!

Usage

The Node documentation states we’ll need a uid and gid as the two parameters for filehandle.chown():

  • uid represents an integer value of the user id you want to change to
  • gid represents an integer value of the group id that user belongs to

Note that the filehandle class is simply a wrapper for a file descriptor (it’s like an improved file system object that closes the file if you forget to!)

Not sure what the possible values for the uid and gid are? We can run one command in our terminal to quickly figure that out:

gid

which will print user and group information for the specified user,
or (when user omitted) for the current user. Running it on my local machine gives me..

uid=999(sean) gid=100(staff) groups=100(staff), ...

gid --help will also shed more light on it’s usage:

Viewing all of the arguments for gid

Now, we can put it together with a simple example:

var fs = require('fs');
var myFile = '~/project/tmp/myFile.txt';
// Change owner of myFile to user sean, belonging to the staff group
fs.chown(myFile, 999, 100, (err) => {
if (err) { throw err; }
});

You can verify that everything worked fine by running ls -l to list all of the files, with their respective file owner:

Viewing the file ownership using ls -l

Final Thoughts

While this function might not be as common as other ones like fs.writeFile() or fs.rmdir(), it still comes in handy! One scenario that I recently ran into was not having execution permission on a Go executable inside a Docker container, even though I had full read-write access. It turns out that I had to change the file owner when copying the contents into the Docker container in order to be able to execute the binary, which prompted me to see if Node had anything to do this 😁

Know any other cool uses for filehandle.chown()? Comment them below ⤵️

Until next time,

Sean 👨🏽‍💻

--

--