-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpstatic.js
47 lines (39 loc) · 1.12 KB
/
httpstatic.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
var http = require('http');
var fs = require('fs');
var path = require('path');
var server = http.createServer();
var notFound = function (response) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/plain');
response.end('I not haz the page');
};
server.on('request', function (request, response) {
var filename = null;
console.log('request received for', request.url);
if (request.url === '/') {
filename = './public/index.html';
}
else {
filename = './public' + request.url;
}
fs.exists(filename, function (exists) {
if (!exists) return notFound(response);
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
var stream = fs.createReadStream(filename);
stream.on('data', function (data) {
response.write(data);
console.log('returning chunk');
});
stream.on('end', function () {
response.end();
console.log('response sent');
});
stream.on('error', function (err) {
console.error('Oh no!', err);
});
});
});
server.listen(8000, function () {
console.log('Server listening on port 8000...');
});