Arvind kr Arvind kr - 4 months ago 13
Node.js Question

Reloading Json file on change

I am using Nodejs Express.I am trying to display the list users from the database to the webpage.So I created a intermediate json file to store all user details and then use it to display in webpage.The server side code updates the json file and database on any new entries or deletions, but the data is not getting reflected in webpage. It gets reflected once i restart the server.

Server.js

app.post('/add', function (req, res) {
new employee({
id : req.body.id,
firstName : req.body.firstName,
lastName : req.body.lastName,
emailId : req.body.emailId
}).save( function ( err, employee, count ){
if( err ) return next( err );
});
var db = new json("user-list",true,false);
var count = db.getData('/count');

//console.log(result[item].firstName)
db.push('/user/'+count+'/firstName',req.body.firstName);
db.push('/user/'+count+'/lastName',req.body.lastName);
db.push('/user/'+count+'/emailId',req.body.emailId);
db.push('/user/'+count+'/id',req.body.id)
db.push('/count',count+1);
db.save();
db.reload();
res.redirect( '/Webpage' );
});


Webpage.js

var users = require('../user-list.json');
router.get('/', function(req, res, next) {

res.render('Webpage', {
title: 'Express' ,
user : users.user
});
});


Webpage.ejs :

<% for(var item in user) { %>
<tr>
<td><%= user[item].id %></td>
<td><%= user[item].firstName %></td>
<td><%= user[item].lastName %></td>
<td><%= user[item].emailId %></td>
<td>
<span onclick="editUser()" class="glyphicon glyphicon-edit"></span>
<span onclick="deleteUser(<%= user[item].id %>)" class="glyphicon glyphicon-remove"></span>
</td>
</tr>
<% }%>


How can i get the data displayed in webpage if any changes have been made? I have browsed for while and found nothing that helps.

Answer

I believe the problem is this:

var users = require('../user-list.json');

The application in Node will not re-load the javascript source files. In turn, anything that the source files require to work will be loaded in this manner - at startup only.

In order for the file to be read per-request you need to manually read the file (using file IO commands in Node) inside router.get('/', function(req, res, next) { ... } ) - as this is the code that runs per page load, not the code above it.

So Webpage.js should look like this:

var fs = require('fs'); // new
router.get('/', function(req, res, next) {
var users = JSON.parse(fs.readFileSync('../user-list.json', 'utf8'));
res.render('Webpage', {
    title: 'Express' ,
    user : users.user
});
});