dave dave - 1 year ago 67
Node.js Question

How to ensure a path is readable and writable, regardless of whether a file exists? NodeJS

My use case is I've been given a directory for config file, which may or may not exist already. If it exists already I would like to read it, if it doesn't I'd like to write some defaults there that can be user-configured via that file in the future.

If I don't have the permissions to read and write to a file at that path (regardless of whether a file is already there) I'd like to report that error so it can be corrected.

Answer Source

This could definitely use some refactoring but seems to be a workable approach. I suspect there is an easier way, though. Still hoping someone else will give a better answer to this.

function canReadAndWrite(targetPath) {
  return new Promise((resolve, reject) => {
    fs.stat(targetPath, (err) => {
      if (err) { reject(err); return; }
      fs.access(targetPath, fs.W_OK | fs.R_OK, (err) => {
        if (err) {
          const dir = path.dirname(targetPath);
          fs.access(dir, fs.W_OK | fs.R_OK, (err) => {
            if (err) { reject(err); return; }


which can be used like:

canReadAndWrite('/var/lib/test/config.json').then((exists) => {
    if (exists) {
        // safely read file
    } else {
        // safely write file
}).catch((error) => {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download