简体   繁体   中英

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 doesPathExist seems 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.

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))
  })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM