Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as http from 'http';
- import * as fs from 'fs';
- import * as url from 'url';
- const port = 5000;
- /* global variables */
- let listingData, server;
- const requestHandler = (request, response) => {
- const parsedUrl = url.parse(request.url);
- if( parsedUrl.pathname == '/listings' ){
- //send listingdata in json format
- //response.writehead(200, {'content-type': 'text/plain':);
- //reponse.writehead(200, { 'application-type': 'application/json' });
- response.write(JSON.stringify(listingData));
- response.writeHead(404, {'Content-Type': 'text/plain'});
- response.end();
- }
- else
- response.writeHead(404);
- //response.end();
- /*
- your request handler should send listingdata in the json format as a response if a get request
- is sent to the '/listings' path. otherwise, it should send a 404 error.
- hint: explore the request object and its properties
- hint: explore the response object and its properties
- https://code.tutsplus.com/tutorials/http-the-protocol-every-web-developer-must-know-part-1--net-31177
- http://stackoverflow.com/questions/17251553/nodejs-request-object-documentation
- hint: explore how callback's work
- http://www.theprojectspot.com/tutorial-post/nodejs-for-beginners-callbacks/4
- hint: explore the list of mime types
- https://developer.mozilla.org/en-us/docs/web/http/basics_of_http/mime_types/complete_list_of_mime_types
- */
- };
- fs.readfile('listings.json', 'utf8', (err, data) => {
- /*
- this callback function should save the data in the listingdata variable,
- then start the server.
- hint: check out this resource on fs.readfile
- //https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
- hint: read up on json parsing node.js
- */
- // check for errors
- if(err){
- console.error(err)
- return
- }
- try{
- listingData = JSON.parse(data)
- }
- catch(err){
- console.error(err)
- }
- // save the sate in the listingdata variable already defined
- //listingdata = json.parse(data);
- const temp = listingData;
- // creates the server
- http.createServer(function (req, res) {
- res.writeHead(404, {'Content-Type': 'text/plain'});
- res.write('Bad gateway error');
- res.end();
- }).listen(port);
- // start the server
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement