Manav Saxena
Manav Saxena

Reputation: 473

Express: sending JSON file as a response

I am new to express. I have made a simple react front-end with express backend using express generators and currently, this is the way I am sending JSON data:-

var express = require("express");
var router = express.Router();

router.get("/", function(req, res, next) {
  var jsonData = {"name": "manav"};
  res.json(jsonData);
});

module.exports = router;

but how can I send data from a JSON file instead? I tried creating a JSON file in the same directory and sending it like res.json('./jsonFile'); but it doesn't work. Could someone help me out please?

Upvotes: 7

Views: 12455

Answers (2)

Try in your code like following to read json file

var fs = require('fs');
var path = require('path')

var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
    var readable = fs.createReadStream(usersFilePath);
    readable.pipe(res);
});

Upvotes: 5

jANVI
jANVI

Reputation: 748

You can do like this :

var hoteljsonFile = require("../data/hotel-data.json"); // path of your json file


router.get("/", function(req, res, next) {

  res.json(hoteljsonFile);
});

Upvotes: 13

Related Questions