-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_server.js
69 lines (64 loc) · 1.81 KB
/
simple_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
var http = require('http'),
fs = require('fs'),
path = require('path'),
ext = /[\w\d_-]+\.[\w\d]+$/;
//Gets the mimetype from extension
function getContentType(fPath) {
var extn, contentType = '',
extStart = fPath.lastIndexOf('.') + 1;
if (extStart > -1 & extStart < fPath.length) {
extn = fPath.substring(extStart);
}
switch (extn) {
case 'js':
contentType = 'application/javascript';
break;
case 'jpg' | 'jpe' | 'jpeg':
contentType = 'image/jpeg';
break;
case 'gif':
contentType = 'image/gif';
break;
case 'png':
contentType = 'image/png';
break;
case 'mp3':
contentType = 'audio/mpeg';
break;
case 'wav':
contentType = 'audio/x-wav';
break;
case 'zip':
contentType = 'application/zip';
break;
default:
contentType = 'text/html';
}
return contentType;
}
http.createServer(function(req, res) {
if (req.url === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
fs.createReadStream('index.html').pipe(res);
}
else if (ext.test(req.url)) {
var fPath = path.join(__dirname, req.url);
fs.exists(fPath, function(exists) {
if (exists) {
res.writeHead(200, {
'Content-Type': getContentType(fPath)
});
fs.createReadStream(fPath).pipe(res);
}
else {
res.writeHead(404, {
'Content-Type': 'text/html'
});
fs.createReadStream('404.html').pipe(res);
}
});
}
}).listen(process.env.PORT, process.env.IP);
console.log('Server running at http://' + process.env.IP + ':' + process.env.PORT + '/');