-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
55 lines (45 loc) · 1.35 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var http = require('http'),
fs = require('fs'),
url = require('url'),
port = 8080;
/* Global variables */
var listingData, server;
var requestHandler = function(request, response) {
var parsedUrl = url.parse(request.url);
/*
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.
*/
// check and see if GET request is sent to the '/listings' path
if(parsedUrl.pathname == '/listings'){
//send listingData as a response
response.write(listingData);
response.end();
}
// send a 404 error
else{
response.writeHead(404);
response.write('Bad gateway error');
response.end();
}
};
// this is readinglistings.json
// either will send what is in this file to the function as data or produce an error err
fs.readFile('listings.json', 'utf8', function(err, data) {
// check for errors
// use err to check
if(err){
throw err;
}
// save the sate in the listingData variable already defined
// if there is no error then save the data in listingData
else{
listingData = data;
}
// create the server
var server = http.createServer(requestHandler);
// start the server
server.listen(port, function() {
console.log('Server listening on: http://127.0.0.1:' + port);
});
});