Dikshitkumar
Dikshitkumar

Reputation: 43

Cannot find module 'fs/promises' even when I use the fs code only inside "getStaticProps()" - next js

So, I use latest version of next js ^11.1.2. According to the documentation, using server side (node js) codes inside getStaticProps() function is fine as it removes the 'fs' import from the client side build.

But in my case its not working.

The following code is what I did...

    import fs from "fs/promises";
    import path from "path";
    
    function HomePage(props) {
      return (
        <ul>
          {props.products.map((el) => (
            <li key={el.id}>{el.title}</li>
          ))}
        </ul>
      );
    }
    
    export async function getStaticProps() {
      try {
        let data = await fs.readFileSync(
          path.join(process.cwd(), "data", "dummy-backend.json")
        );
        console.log(data);
        data = JSON.parse(data);
        return {
          props: {
            products: data.products,
          },
        };
      } catch (err) {
        console.log(err);
        return {
          props: {
            products: [],
            error: "Error in fetching data",
          },
        };
      }
    }
    
    export default HomePage;

Picture of the error displayed in the terminal

And I'm in the development environment.

Upvotes: 3

Views: 10882

Answers (1)

Efe Celik
Efe Celik

Reputation: 546

Use

import { promises as fs } from 'fs';

Instead of

import fs from "fs/promises";

and change fs.readFileSync to fs.readFile.

Upvotes: 7

Related Questions