-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
91 lines (83 loc) · 1.59 KB
/
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
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
90
91
var httpServer = function(dir)
{
var http = require('http');
var fs = require('fs');
var path = require("path");
var url = require('url');
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"
};
return http.createServer(function(req, res)
{
var uri = url.parse(req.url)
.pathname;
var filename = path.join(dir, unescape(uri));
var indexFilename = path.join(dir, unescape('index.html'));
var stats;
console.log(filename);
try
{
stats = fs.lstatSync(filename); // throws if path doesn't exist
}
catch (e)
{
res.writeHead(404,
{
'Content-Type': 'text/plain'
});
res.write('404 Not Found\n');
res.end();
return;
}
var fileStream;
if (stats.isFile())
{
// path exists, is a file
var mimeType = mimeTypes[path.extname(filename)
.split(".")[1]];
res.writeHead(200,
{
'Content-Type': mimeType
});
fileStream =
fs
.createReadStream(filename)
.pipe(res);
}
else if (stats.isDirectory())
{
// path exists, is a directory
res.writeHead(200,
{
'Content-Type': "text/html"
});
fileStream =
fs
.createReadStream(indexFilename)
.pipe(res);
}
else
{
// Symbolic link, other?
// TODO: follow symlinks? security?
res.writeHead(500,
{
'Content-Type': 'text/plain'
});
res.write('500 Internal server error\n');
res.end();
}
});
};
var port = 18080;
var HTTPserver =
httpServer('./')
.listen(port, function()
{
console.log('HTTP listening : ' + port);
});