forked from celyes/Node-static-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
27 lines (25 loc) · 846 Bytes
/
app.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
const fs = require('fs');
const http = require('http');
const url = require('url');
const routes = require('./routes');
let port = 3000;
// Function to send 404 response
function send404Response(response){
response.writeHead(404, {"Content-Type": "text/html"});
fs.createReadStream("./public/404.html").pipe(response);
}
// Function to check if the server has started
function hasStarted(port){
console.info('Server started at http://localhost:' + port);
}
// Function that handles the routing process
function onRequest(request, response){
let q = url.parse(request.url, true);
if(q.pathname in routes){
console.log('requested url : ' + q.pathname);
return routes[q.pathname](request, response);
}
send404Response(response);
}
// Magic !
http.createServer(onRequest).listen(port, hasStarted(port));