Challenge 1

In notebook:
FrontEndMasters Building Web Apps with Node.js
Created at:
2015-10-08
Updated:
2015-10-08
Tags:
backend Node JS JavaScript
Video Course on Building Web Applications with Node.jstip: convert a csv file to a JSON object:
split on lines: var lines = data.split('\n');
split the parts on line and add them to a cumulator (this example is just for value pairs)
lines.forEach(function(line) {
  var parts = line.split(',');
  responseData[parts[0]] = parts[1]; 
});

Solution.

  • require the ​http​ and ​fs​ modules
  • create a news httpserver to serve the resulting JSON file
  • read the file
  • manipulate the file data
  • start the response with ​writeHead​ 
  • end the response with the data: response.end(JSON.stringify(responseData));
  // Load module dependencies
var http = require('http'),
    fs = require('fs');

http.createServer(function(request, response) {

    // TODO: Find the ASYNCHRONOUS, NON-BLOCKING API for reading in a file.
    fs.readFile('./data.csv', 'utf-8', function(err, data) {
        var responseData = {};

        // Basic JS: Work with the data in the file, and create the response
        var lines = data.split('\n');

        // Note the native forEach support in Arrays in node.js!
        lines.forEach(function(line) {
            var parts = line.split(',');
            responseData[parts[0]] = parts[1];
        });

        // TODO: How do we set the content type we're sending back?
        response.writeHead(200, {
            'Content-Type':'application/json'
        });

        // TODO: How do we serialize responseData to a JSON string?
        response.end(JSON.stringify(responseData));

    });

}).listen(3000);

console.log('node server running on port 3000');
'​response'​ in the previous example
is an ​http.ServerResponse​ object