Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving json from a file express js

Newbie to express, I have a folder that has a db.json file and it gets replaced with a new db.json every 11 seceonds. What is the best way to let express.js serve it so that new content shows on api call? This is what I have so far:

const express = require('express');
const router = express.Router();

router.get('/api/items', (req, res) => {
  let dbPath = require('./data/db.json');
  res.send(JSON.stringify(dbPath));

});

db.json looks something like this

[{"recordType": "E90", "count": "55", "space": "4" },
{"recordType": "A48", "count": "40", "space": "5" }, ....]

Problem: I'm not seeing the updated value next time I make the api call.

like image 803
jeesan485 Avatar asked Nov 28 '17 19:11

jeesan485


People also ask

How do I read a JSON file in node JS?

To load the data from customer. json file, we will use fs. readFile , passing it the path to our file, an optional encoding type, and a callback to receive the file data. If the file is successfully read, the contents will be passed to the callback.

How do I return a JSON object in node JS?

Go to http://localhost:3000/multiple, you will see the following output. Go to http://localhost:3000/array, you will see the following output. Method 2 (Using HTTP interface): Although the first method is sufficient for most solutions, there is another method that uses HTTP interface by Node. js and returns JSON data.

How js store data from JSON file?

If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.


1 Answers

Try this:

const fs = require('fs');

router.get('/api/items', (req, res) => {

    fs.readFile('./data/db.json', (err, json) => {
        let obj = JSON.parse(json);
        res.json(obj);
    });

});

Hope this helps

like image 81
YouneL Avatar answered Sep 27 '22 23:09

YouneL