Node.js File System Features

Alex Kong
2 min readSep 17, 2018

--

This post was done as a part of the first lab for the DPS909 Open Source course. This post explores the Node.js fs module’s access method.

The fs.access(path[, mode], callback)method is used to test the user’s permissions for a file and takes 3 arguments, 1 of which is optional:

  • path can be a string, buffer or URL
  • mode is an optional argument which specifies which permissions checks the method will perform. There are four different File Access Constants: F_OK, the default if no mode is set, will check if the file exists. R_OK checks if the file can be read. W_OK checks if the file can be written to. X_OK checks if the file can be executed (this behaves like F_OK on Windows). Multiple permissions can be checked with a single call using a bitwise OR mask. For example the read and write permission can be checked with the mask: fs.constants.R_OK | fs.constants.W_OK
  • callback is the callback function that is called when an error does occur.

The following is a function that checks if a file exists and can be written to:

fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
if (err) {
console.error(
`${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
} else {
console.log(`${file} exists, and it is writable`);
}
});

Ok, let’s see if this works! My Desktop folder is set to Read-only

With any luck our code should pick up that the Desktop folder exists but cannot be written to.

Looks like the code is working as intended!

--

--