Cannot read property 'F_OK' of undefined in NodeJS

Viewed 2461

I'm trying to use ExcelJS in NestJS. For some reason, I can not open xlsx file.

exceljs uses this code for checking if file exists

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

that code returns Cannot read property 'F_OK' of undefined. Console.log on line 4 returns path I send it correctly

However, if I try to access the same file form my service with this code

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

That code returns "file.xlsx exists, and it is writable". What is the difference and why I can't read the same file with exceljs?

1 Answers

I had the same problem.

The reason was because I was importing fs/promises and the constants are storaged in fs

Basically, you are trying to get the constants from a place where they were not declared.

This is how I solved:

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

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

You can see that for access I use fsp.access and for the constants fs.constants.F_OK

Related