Advertisement
calebbot

Untitled

Jan 20th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. import * as http from 'http';
  2. import * as fs from 'fs';
  3. import * as url from 'url';
  4.  
  5. const port = 5000;
  6.  
  7. /* global variables */
  8. let listingData, server;
  9.  
  10. const requestHandler = (request, response) => {
  11. const parsedUrl = url.parse(request.url);
  12.  
  13. if( parsedUrl.pathname == '/listings' ){
  14. //send listingdata in json format
  15. //response.writehead(200, {'content-type': 'text/plain':);
  16. //reponse.writehead(200, { 'application-type': 'application/json' });
  17. response.write(JSON.stringify(listingData));
  18. response.writeHead(404, {'Content-Type': 'text/plain'});
  19. response.end();
  20. }
  21. else
  22. response.writeHead(404);
  23. //response.end();
  24.  
  25.  
  26.  
  27. /*
  28. your request handler should send listingdata in the json format as a response if a get request
  29. is sent to the '/listings' path. otherwise, it should send a 404 error.
  30.  
  31. hint: explore the request object and its properties
  32. hint: explore the response object and its properties
  33. https://code.tutsplus.com/tutorials/http-the-protocol-every-web-developer-must-know-part-1--net-31177
  34. http://stackoverflow.com/questions/17251553/nodejs-request-object-documentation
  35.  
  36. hint: explore how callback's work
  37. http://www.theprojectspot.com/tutorial-post/nodejs-for-beginners-callbacks/4
  38.  
  39. hint: explore the list of mime types
  40. https://developer.mozilla.org/en-us/docs/web/http/basics_of_http/mime_types/complete_list_of_mime_types
  41.  
  42. */
  43.  
  44.  
  45. };
  46.  
  47. fs.readfile('listings.json', 'utf8', (err, data) => {
  48. /*
  49. this callback function should save the data in the listingdata variable,
  50. then start the server.
  51.  
  52. hint: check out this resource on fs.readfile
  53. //https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
  54.  
  55. hint: read up on json parsing node.js
  56. */
  57.  
  58.  
  59. // check for errors
  60. if(err){
  61. console.error(err)
  62. return
  63. }
  64. try{
  65. listingData = JSON.parse(data)
  66. }
  67. catch(err){
  68. console.error(err)
  69. }
  70.  
  71. // save the sate in the listingdata variable already defined
  72. //listingdata = json.parse(data);
  73. const temp = listingData;
  74.  
  75. // creates the server
  76.  
  77. http.createServer(function (req, res) {
  78. res.writeHead(404, {'Content-Type': 'text/plain'});
  79. res.write('Bad gateway error');
  80. res.end();
  81. }).listen(port);
  82. // start the server
  83.  
  84. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement