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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With