Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

399
Visualizações
How to send data read from file as response from an express route in NodeJS?

I have a JSON file in local folder with a structure like this.

{
   license: "abcd",
   name: "abcd",

   data: [
      Array of JSON Objects ....
   ]
}

I want to access the data array in the Object and send it as response from express route This is what I tried.

import express from "express";
import fs from "fs";
import bodyParser from "body-parser";

var app = express();
app.use(bodyParser.json());

var fileData: string = fs.readFileSync("path to json file", { encoding: 'utf-8' });
var jsonData = JSON.parse(fileData).data;

console.log(jsonData);

app.get("/getJsonData", (err, res) => {
    if (err)
        throw err;

    res.send(JSON.stringify(jsonData));
});

app.listen("3001", () => console.log("listening at 3001"));

It shows correct json when I log it outside the express route function, but inside the function the response is [object Object] with status code of 500 (Internal Server Error).

I tried the asynchronous method also

var app = express();
app.use(bodyParser.json());

app.get("/getJsonData", (err, res) => {
    if (err)
        throw err;

    fs.readFile("path to json file", (fileErr, result) => {
        if(fileErr) throw fileErr;

        var jsonData = JSON.parse(result.toString()).data;

        res.json(jsonData);
    });
    
});

but I get the same response as [object Object] and status code 500. I tried res.send(JSON.stringify(jsonData)) but no use. How can I send the json data that I get from file to frontend using Express?? btw I am using TypeScript for this.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

This line

app.get("/getJsonData", (err, res) => 

The err is not an error, its the request it should be:

app.get("/getJsonData", (req, res) => {
    res.send(JSON.stringify(jsonData));
});

Its literally at the example Hello world site of express.js, there you will sees that they use req

https://expressjs.com/de/starter/hello-world.html

The reason why you always get an 500 error is because err, wich is obviously the request, is always truthy

You also dont need to Stringify it, you could just do res.json(jsonData)

over 4 years ago · Santiago Trujillo Relatório

0

If you want to send a json object between your express server and the client, you'll need to send the data via res.json(obj) where obj must explicitly be a JSON object (can't be an array of JSON objects). What you can do to just send the array, is simply wrap your jsonData array inside a bracket pair and you are done.

let jsonData = JSON.parse(fileData).data;
res.json({ jsonData });
//or if you dont understand the above use
res.json({ jsonData: jsonData})
//which is equivalent to the above line
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda