I was working on a Next js blog, I have completed the frontend and I was making backend using the next js
./pages/api
I made a file
./pages/api/blogs.js
I made some json files in ./data
folder as dummy data
./data/hello.json
{
"title" : "This is hello",
"description" : "This is description",
"content" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto quasi error cumque iure tempore officiis quaerat rerum delectus hic reprehenderit. Iure, eveniet repudiandae. Consequuntur obcaecati eius sequi similique officia beatae quibusdam blanditiis."
}
I write this code in ./pages/api/blogs.js
import * as fs from 'fs'
export default function handler(req, res) {
fs.readFile("../../data/hello.json", (err,data)=>{
console.log(data)
})
res.status(200).json({"name" : "Shivam Bhai"})
}
but my server console is showing undefined. I also tried loging err on console and this was result
[Error: ENOENT: no such file or directory, open 'C:\projects\data\hello.json'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\projects\\data\\hello.json'
}
But I have made this directory. screenshot of the filesystem used in project how do I fix this problem?
You should use the address this way :
import * as fs from 'fs'
export default function handler(req, res) {
fs.readFile("data/hello.json", (err,data)=>{
console.log(data)
})
res.status(200).json({"name" : "Shivam Bhai"})
}
It's always a good idea to also use __dirname
for addressing like below:
import * as fs from 'fs'
export default function handler(req, res) {
fs.readFile(__dirname + "/../../data/hello.json", (err,data)=>{
console.log(data)
})
res.status(200).json({"name" : "Shivam Bhai"})
}