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.
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.
Share Improve this question asked Oct 14, 2021 at 6:57 DikshitkumarDikshitkumar 431 gold badge1 silver badge6 bronze badges 2-
2
Which Node.js version are you using?
fs/promises
is not available on versions less than 14. – brc-dd Commented Oct 14, 2021 at 7:28 - I was using node js v12.16.2. – Dikshitkumar Commented Oct 14, 2021 at 7:32
1 Answer
Reset to default 7Use
import { promises as fs } from 'fs';
Instead of
import fs from "fs/promises";
and change fs.readFileSync
to fs.readFile
.