首页 > 解决方案 > 无法读取 NodeJS 中未定义的属性“F_OK”

问题描述

我正在尝试在 NestJS 中使用 ExcelJS。由于某种原因,我无法打开 xlsx 文件。

exceljs 使用此代码检查文件是否存在

  fs: {
    exists: function exists(path) {
      return new Promise(function (resolve) {
        console.log(path);
        fs.access(path, fs.constants.F_OK, function (err) {
          resolve(!err);
        });
      });
    }
  },

该代码返回无法读取未定义的属性“F_OK”。第 4 行的 Console.log 返回我正确发送的路径

但是,如果我尝试使用此代码从我的服务访问相同的文件

    fs.access(this.file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
        if (err) {
            console.error(
                `${this.file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
        } else {
            console.log(`${this.file} exists, and it is writable`);
        }
    });

该代码返回“file.xlsx 存在,并且它是可写的”。有什么区别,为什么我不能用 exceljs 读取同一个文件?

标签: node.jsnestjs

解决方案


我有同样的问题。

原因是因为我正在导入fs/promises并且constants存储在fs

基本上,您正在尝试constants从未声明它们的地方获取。

我就是这样解决的:

import fsp from 'fs/promises'
import fs from 'fs'

await fsp.access(testDir, fs.constants.F_OK);

你可以看到 for accessI usefsp.access和 for theconstants fs.constants.F_OK


推荐阅读