forked from cs4241-19a/a1-gettingstarted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (72 loc) · 1.92 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*const http = require('http'),
fs = require('fs'),
mime = require('mime'),
port = 3000
const sendFile = function (r, name){
const mimeType = mime.getType(name)
r.writeHeader(200, {'Content-Type' : mimeType})
fs.readFile( name, function( err, content ) {
r.end( content, 'utf-8' )
})
}
let file
fs.readFile( 'index.html', function( err, content ) {
file = content
})
let ss
fs.readFile('style.css', function(e, css){
ss = css
})
let ttf
fs.readFile('Milkshake.ttf', function(e, font){
ttf = font
})
const server = http.createServer( function( request,response ) {
const url = request.url.slice(1)
console.log(request.url)
switch( request.url) {
case '/':
sendFile(response, 'index.html')
break
case '/style.css':
response.end(ss, 'utf-8')
case '/Milkshake.ttf':
response.end(ttf, 'utf-8')
case '/onLoad.js':
response.end()
default:
response.end( '404 Error: File Not Found' )
}
})
server.listen( process.env.PORT || port )
*/
/* the part above was the server I wrote before I saw the improved server */
const http = require( 'http' ),
fs = require( 'fs' ),
mime = require( 'mime' ),
port = 3000
const server = http.createServer( function( request,response ) {
const filename = request.url.slice( 1 )
console.log( filename )
switch( filename ) {
case '':
if( request.url === '/' ) sendFile( response, 'index.html' )
break
default:
sendFile( response, filename )
break
}
})
server.listen( process.env.PORT || port )
const sendFile = function( response, filename ) {
const type = mime.getType( filename )
fs.readFile( filename, function( err, content ) {
if( err === null ) {
response.writeHeader( 200, { 'Content-Type': type })
response.end( content )
}else{
response.writeHeader( 404 )
response.end( '404 Error: File Not Found' )
}
})
}