86

I'm just trying to read a file using fs.readFileSync, though it seems it cannot be found.

I made sure to declare it, added it within my constructor:

export default class Login extends React.Component<LoginProps, {}> {
    private webAuth: auth0.WebAuth;
    fs: any;

    constructor(props: any, context: any) {
        super(props, context);
        this.fs = require('fs');
        this.webAuth = new auth0.WebAuth({
            clientID: conf.auth0.clientId,
            domain: conf.auth0.domain,
            responseType: 'token id_token',
            redirectUri: `${window.location.origin}/login`
        });
    }
[...]

And used it in a simple function:

verifyToken = (token) => {

    console.log(this.fs);
    let contents = this.fs.readFileSync('../utils/public.key', 'utf8');
    console.log(contents);

}

But this raises an Uncaught TypeError: _this.fs.readFileSync is not a function. Is there a special way to include fs in Typescript ?

2
  • 3
    this your Login component is a browser component, right? Why are you trying to use the fs module?
    – Diullei
    Commented Mar 27, 2017 at 13:51
  • If you are using wepback you could require file contents using raw-loader. Commented Mar 27, 2017 at 14:02

4 Answers 4

129

I can't imagine any case in which you would use fs inside a React component. Even though you can use React in the server to render stuff, the same code is supposed to run in the client, there's no way you can access fs in the client.

If you want to use fs in the server, this is an example:

import * as fs from 'fs';
import * as path from 'path';
fs.readFile(path.join(__dirname, '../../client/index.html'), 'utf8', (error, data) => {
        // ...
    })

On your package.json file, make sure to have a dependency on node

"dependencies": {
 "@types/node": "^7.0.5"
}

And this is how my tsconfig.json file looks like:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "allowJs": true,
        "typeRoots": [
            "./node_modules/@types"
        ]
    },
    "include": [
        "./db/**/*",
        "./src/**/*"
    ]
}
3
  • 4
    fs, in my case, is used to open a file that contains an Auth0 public key, which is used to verify a jwt token. I'm still fairly new to React, thanks for the advice ! Commented Mar 27, 2017 at 15:37
  • The command of the npm install @types/node did it for me.
    – Julian
    Commented Mar 8, 2021 at 22:17
  • In the code you provided you are using es modules, but in your tsconfig you are using commonjs modules. This will not work.
    – m_jdm35
    Commented May 22 at 11:05
21

Using node -v 10.15.0 and @types/node:

It seems declaration has been rewritten...

fs definition is declared as a module so you should do:

import fs from "fs"; // Without star

compiled:

var fs_1 = __importDefault(require("fs"));

or

const fs = require("fs"); instead of require("fs").default;

with star you will have fs.default.TheFunctionYouWant instead of fs.TheFunctionYouWant

The better way is to console.log(fs); to see what it is imported.

{
  "compilerOptions": {
    "typeRoots": [],
    "types": [
      "node"
    ]
  }
}
14

Latest implantation, you can import methods.

import { readFile, writeFile } from 'fs/promises';

And use directly...

// write
await writeFile('./file.json', content);

// read
const content = await readFile('./file.json');

Reference https://nodejs.org/docs/latest-v14.x/api/

5
  • Is this possible to implement in React? (TSX)
    – Hugobop
    Commented Mar 30, 2023 at 22:18
  • 1
    I never try, but I believe it. Commented Apr 6, 2023 at 12:21
  • 3
    Don't forget to add @types/node to package.json: "devDependencies": { "@types/node": "^20.3.3" } Commented Jul 2, 2023 at 20:38
  • do i need to install fs/promises
    – Rajib
    Commented Feb 7 at 20:49
  • No, fs is a native library. Commented Feb 7 at 22:40
4

It may also help to install @types/node: npm i --save-dev @types/node

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.