Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

458
Views
Node js fs is showing undefined on console.log

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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"})
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!