Arvind kr Arvind kr - 1 year ago 147
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'/add', function (req, res) {
new employee({
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');

res.redirect( '/Webpage' );


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) { %>
<td><%= user[item].id %></td>
<td><%= user[item].firstName %></td>
<td><%= user[item].lastName %></td>
<td><%= user[item].emailId %></td>
<span onclick="editUser()" class="glyphicon glyphicon-edit"></span>
<span onclick="deleteUser(<%= user[item].id %>)" class="glyphicon glyphicon-remove"></span>
<% }%>

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download