fs.readFile() or fs.readFileSync() not a function exception but why?

13,087

Solution 1

Because fs does not have a default export you need to import like so:

import * as fs from 'fs'

Solution 2

You are mixing javascript standards.

If you choose to use the older javascript ES5 standard, then your code should like like this:

var fs = require('fs');

However, if you're going to use the newer ES6 (and beyond) standard, you would use the import statement like so:

import fs from 'fs';

You seem to be combining the two, hence your error.

NOTE: Because fs has a default export that exports the fs module, you don't need the import * as syntax. See this post for a more detailed explanation.

Share:
13,087
Xin Qian
Author by

Xin Qian

Updated on June 28, 2022

Comments

  • Xin Qian
    Xin Qian almost 2 years

    I am using the fs module with the following import code

    import fs = require('fs')

    The code runs until encountering this exception at the second line of the TypeScript codes below

    const filePath = 'data/soylent-uist2010/userSegments.json'
    const seg = fs.readFileSync(filePath, {
      encoding: 'utf8',
    })
    

    However, if I supply the path argument of readFileSync as a raw string (as below), it works as normal (value is assigned).

    const seg = fs.readFileSync('data/soylent-uist2010/userSegments.json', {
      encoding: 'utf8',
    })
    

    The error stack trace is as below,

    Viewer.tsx:155 Uncaught (in promise) TypeError: fs.readFileSync is not a function
        at Viewer.<anonymous> (Viewer.tsx:155)
        at step (io.ts:106)
        at Object.next (io.ts:106)
        at io.ts:106
        at new Promise (<anonymous>)
        at __awaiter (io.ts:106)
        at Viewer._this.loadFiles (Viewer.tsx:135)
        at Viewer.<anonymous> (Viewer.tsx:98)
        at step (io.ts:106)
        at Object.next (io.ts:106)
    

    A longer code snippet is as below. I suspect if the async keyword (in the class method) would require an await keyword before fs.readFile()

      loadFiles = async () => {
        this.setState({ pages: [] });
        const {
          pageNumbersToLoad,
          pathInfo: { pdfDir, pdfRootDir }
        } = this.props;
        const fullDirPath = path.join(pdfRootDir, pdfDir);
        const pdfPath = path.join(fullDirPath, pdfDir + ".pdf");
        **const seg = fs.readFile(...);**
    
  • Dentrax
    Dentrax about 2 years
    ES6 way throws: "fs__WEBPACK_IMPORTED_MODULE_3___default().readFileSync is not a function"