Search code examples
javascriptjsondust.js

How do you dynamically populate dust template with JSON response from server?


I am attempting to hit a URL and get JSON in response. I want to use some of the values from the JSON to populate a DUST template which will show the data in a simple html table. I have the following method to get the data, but I am unsure of how I should populate the dust template.

'use strict';
var http = require("http");
    url = "http://api.wunderground.com/api/b3dd03e008742886/forecast/q/MD/Timonium.json";
var data;

var request = http.get(url, function (response) {
    console.log("Hitting url: " + url);
    // data is streamed in chunks from the server
    // so we have to handle the "data" event    
    var buffer = "";

    response.on("data", function (chunk) {
        buffer += chunk;
    }); 

    response.on("end", function (err) {
        // finished transferring data
        // dump the raw data
    //    console.log(buffer);
    //    console.log("\n");
        data = JSON.stringify(buffer);
    }); 
}); 


module.exports = function (server) {

    server.get('/', function (req, res) {
        var model = { name: 'weather' };

        console.log(data);

        res.render('index', model);

    });

};

Now I have a simple model that contains a name attribute. I want to change that to grab the values I want from the JSON and insert them into the model?


Solution

  • Make the request inside the get function like this.

    module.exports = function(server) {
    
        server.get('/', function(req, res) {
            http.get(url, function(response) {
                console.log("Hitting url: " + url);
                var buffer = "";
    
                response.on("data", function(chunk) {
                    buffer += chunk;
                });
    
                response.on("end", function(err) {
                    res.render('index', JSON.stringify(buffer));
                });
            });
        });
    };