Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js fs.access returns undefined no matter what

Here’s the code:

import * as path from 'path';
import * as fs from 'fs';

const doesPathExist = async (path: string) => {
  return await fs.access(path, fs.constants.R_OK, (err) => {
    return err ? false : true;
  });
};

const someFunc = async (documentName: string) => {
  const documentPath = path.join(__dirname, documentName);
  const pathExists = doesPathExist(documentName);
};

The function doesPathExistseems to return Promise<void>, making the pathExists variable undefined no matter the outcome. I’ve tried initializing a temp variable at the top of the function before running fs.access and changing its value inside the callback but still no luck.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is with fs.access, this function does not return a Promise or anything else.

There are a few options to solve it.

  1. you can always use fs.accessSync()
const doesPathExist = async (path: string) => {
  try {
    fs.accessSync(path, fs.constants.R_OK)
    return true
  } catch (e) {
    return false
  }
};
  1. Use fs.promises
const fsPromises = fs.promises;

const doesPathExistB = async (path: string) => {
  try {
    await fsPromises.access(path, fs.constants.R_OK)
    return true
  } catch (e) {
    return false
  }
};
// OR
const doesPathExistA = async (path: string) => {
  return new Promise(async (resolve) => {
    await fsPromises.access(path, fs.constants.R_OK)
      .then(() => resolve(true))
      .catch(() => resolve(false))
  })
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading