Thursday, 8 June 2017

Updating Node.js Handlebars Dynamically Upon Received Data?

I have a project, in which I use the request package to get JSON objects from an array of URLs. Problem is, that the HTML won't be rendered before all the requests have been made. I'm lookingfor a way to dynamically update the HTML table with the new objects, as they are received.

var servers = [{ip:"215.x.x.57", port:8080}, {ip:"215.x.x.58", port:8080}];
router.get('/getInfo', function(req, res){
var bodies = [];  
var len = 0;  
for(var i=0,length=servers.length;i<length;i++){
var theUrl = "http://"+servers[i].ip+":"+servers[i].port+'/getInfo'; 
var options = {
  url: theUrl,
  timeout: 3000
};      

request(options, function (error, response, body) {
if(!error){
  console.log('statusCode:', response && response.statusCode); 
  console.log('body:', JSON.parse(body));
  bodies.push(JSON.parse(body));
}

console.log('error:', error);
len++;

if(len >= servers.length){
  var bodyObject = {bodies};  
  renderBody(res, bodyObject);     
    } 
   }); 
  }
 });


function renderBody(res, bodies){
  res.render('info', bodies);
};

 <info.js route is empty at this time>
 <info.handlebar template file>
 <table class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Height</th>
        </tr>
    </thead>
    <tbody>

     <tr>
     <td></td>
     <td></td>
     <td></td>
     </tr>

    </tbody>
    </table>

Doing it this way 'hangs' the rendering of the HTML page untill all the requests have been made. I would rather have an empty table, and then whenever a request is done, insert the data into said table inside the handlebar template.



via Matt DeVenge

No comments:

Post a Comment