forked from mrdoob/three.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplehttpserver.js
More file actions
101 lines (76 loc) · 2.4 KB
/
Copy pathsimplehttpserver.js
File metadata and controls
101 lines (76 loc) · 2.4 KB
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
92
93
94
95
96
97
98
99
100
101
/**
* a barebones HTTP server in JS
* to serve three.js easily
*
* @author zz85 https://github.com/zz85
*
* Usage: node simplehttpserver.js <port number>
*
* do not use in production servers
* and try
* npm install http-server -g
* instead.
*/
var port = 8000,
http = require('http'),
urlParser = require('url'),
fs = require('fs'),
path = require('path'),
currentDir = process.cwd();
port = process.argv[2] ? parseInt(process.argv[2], 0) : port;
function handleRequest(request, response) {
var urlObject = urlParser.parse(request.url, true);
var pathname = decodeURIComponent(urlObject.pathname);
console.log('[' + (new Date()).toUTCString() + '] ' + '"' + request.method + ' ' + pathname + '"');
var filePath = path.join(currentDir, pathname);
fs.stat(filePath, function(err, stats) {
if (err) {
response.writeHead(404, {});
response.end('File not found!');
return;
}
if (stats.isFile()) {
fs.readFile(filePath, function(err, data) {
if (err) {
response.writeHead(404, {});
response.end('Opps. Resource not found');
return;
}
response.writeHead(200, {});
response.write(data);
response.end();
});
} else if (stats.isDirectory()) {
fs.readdir(filePath, function(error, files) {
if (error) {
response.writeHead(500, {});
response.end();
return;
}
var l = pathname.length;
if (pathname.substring(l-1)!='/') pathname += '/';
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('<!DOCTYPE html>\n<html><head><meta charset="UTF-8"><title>' + filePath + '</title></head><body>');
response.write('<h1>' + filePath + '</h1>');
response.write('<ul style="list-style:none;font-family:courier new;">');
files.unshift('.', '..');
files.forEach(function(item) {
var urlpath = pathname + item,
itemStats = fs.statSync(currentDir + urlpath);
if (itemStats.isDirectory()) {
urlpath += '/';
item += '/';
}
response.write('<li><a href="'+ urlpath + '">' + item + '</a></li>');
});
response.end('</ul></body></html>');
});
}
});
}
http.createServer(handleRequest).listen(port);
require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
console.log('Running at http://' + addr + ((port === 80) ? '' : ':') + port + '/');
})
console.log('Three.js server has started...');
console.log('Base directory at ' + currentDir);