简体   繁体   English

Node.js fs.access 无论如何都会返回 undefined

[英]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. function doesPathExist似乎返回Promise<void> ,无论结果如何,都使pathExists变量undefined 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.在运行fs.access并在回调中更改其值之前,我尝试在 function 顶部初始化一个临时变量,但仍然没有运气。

The issue is with fs.access , this function does not return a Promise or anything else.问题在于fs.access ,这个 function 不返回 Promise 或其他任何东西。

There are a few options to solve it.有几个选项可以解决它。

  1. you can always use fs.accessSync()你总是可以使用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使用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))
  })
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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