Friday, December 9, 2016

JSON Me solution and explanation

“JSON Me”


Directions:
Write a server that reads a file when it receives a GET request from a webpage, then parse the file’s contents into JSON format, and then output the JSON to the client(the browser).
·         The port is passed in process.argv[2].  The file name is passed in process.argv[3].
·         Respond with:    res.json(object)
·         Everything should match the '/books' resource path.
Code:
var express = require('express')
var fs = require('fs')
var app = express();
app.set('json spaces', 0);  // this was a workaround to prevent a common error
app.get('/books', function (req, res) {  // “When a GET request is made to the home page, do this” (per the directions, everything matches the '/books' resource path)
                         var filename = process.argv[3]  // “Point ‘filename’ to this array” The file name is passed in process.argv[3] per the instructions
                   fs.readFile(filename, function(e, data) { // “Read the file and save it to memory, or return an error
                  if (e) return res.send(500)
                 try {
                 books = JSON.parse(data)  // “take what is read, parse it into JSON, and point ‘books’ at the JSON data
                 } catch (e) {      res.send(500)
                }
                          //res.send(books) 
                       res.json(books) // “this is the response to the page
                  }) //end of readFile
}) //end of GET
app.listen(process.argv[2])  // “OK, to get the ball rolling, listen for requests at this port


OUTPUT:

"[{\"title\":\"Express.js Guide\",\"tags\":[\"node.js\",\"express.js\"],\"url\":\"http://expressjsguide.com\"},{\"title\":\"Rapid Prototyping with JS\",\"tags\":[\"backbone.js\",\"node.js\",\"mongodb\"],\"url\":\"http://rpjs.co\"},{\"title\":\"JavaScript: The Good Parts\",\"tags\":[\"javascript\"]}]" 

No comments:

Post a Comment