Home > OS >  Updating Json file in node but fiving previously saved results
Updating Json file in node but fiving previously saved results

Time:10-08

I have a simple node script in which I update the db.json file through the form. It updates the file but when I render it in response for a get or post out it gives previous results only.

var cors = require('cors')


const express = require('express');
const app = express();
var jsonfile = require('jsonfile');    
var file = './db.json'
var filex = require('./db.json')
app.engine('html', require('ejs').renderFile);

app.use(cors())

const http = require('http');
const port = process.env.PORT || 3000

const bp = require('body-parser')
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))

app.set('view engine', 'html')
// Defining get request at '/' route
app.get('/', function(req, res) {

    res.send("<html><head><title>Json</title></head><body><form id='form1' action='/gettingdata' method='post'><input type='text' name='usrid' /><button type='submit' form='form1' value='Submit'>Submit</button></form></body></html>")
});
app.post('/gettingdata',function(req,res){
    
    var user_id = req.body.usrid;
    
    var obj = JSON.parse(user_id)
    jsonfile.writeFileSync(file, obj,{flag: 'w'});
    res.send('updated');

})
app.post('/api',function(req,res){
    res.send(filex)
})
app.get('/api',function(req,res){
    res.send(filex)
})

//extra

app.post('/api/v1/users/initial_authentication',function(req,res){
    res.send(filex)
})
app.get('/api/v1/users/initial_authentication',function(req,res){
    res.send(filex)
})

app.listen(port, function(req, res) {
console.log("Server is running at port 3000");
});

It only gives updated results on redeveloping of server.

CodePudding user response:

var filex = require('./db.json')

So, filex only load the file when the server starts. If you try to get the most updated content of file db.json, please re-load the file.

I guess res.send(require('./db.json')) may work as expected.

CodePudding user response:

I have solved this issue using delete require.cache[require.resolve('./db.json')]

  • Related