繁体   English   中英

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

[英]Node.js fs.access returns undefined no matter what

这是代码:

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

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

问题在于fs.access ,这个 function 不返回 Promise 或其他任何东西。

有几个选项可以解决它。

  1. 你总是可以使用fs.accessSync()
const doesPathExist = async (path: string) => {
  try {
    fs.accessSync(path, fs.constants.R_OK)
    return true
  } catch (e) {
    return false
  }
};
  1. 使用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