Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

457
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda