簡體   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