DPS909 LAB 1

In this post I will be going into detail about two Node.js fs modules: fs.access and fs.accessSync.

The purpose of the fs.access(path[, mode], callback) method is to check if a user have permissions for the given file or path. like the following example.

fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
if (err)
return console.error('no access')
console.log('access for read/write')

  • path takes a string, Buffer, or URL to specify file or directory.
  • mode takes an optional integer to specify accessibility checks that need to be performed.
  • The default mode argument is fs.constants.F_OK (to check of the path is visible to the calling process
  • The callback function is invoked with a possible error argument.

Other constants exposed for permission checking include:

  • fs.constants.R_OK– to check if the path can be read by the process
  • fs.constants.W_OK– to check if the path can be written by the process.
  • fs.constants.X_OK– to check if the path can be executed by the process.

Important: Using fs.access to check for the accessibility of a file before calling fs.open, fs.readFile or fs.writeFile is not recommended because a rare condition will be introduced. Between checking and the actual file operation, another process may have already changed that file. Instead, the file should be opened directly and the error cases should be handled there.

fs.accessSync(path[, mode]) is a module that synchronously (occurring at regular intervals) tests a user’s permissions for the file or directory that is specified by the path. The mode argument is considered optional (integer) and specifies the accessibility checks that need to be performed.

require('fs').accessSync("filename.ext", fs.R_OK | fs.W_OK)
//code to action if file exists
console.log('can read/write');
//if accessibility checks fail, an Error will be thrown