source: other-projects/playing-in-the-street/summer-2013/trunk/Playing-in-the-Street-WPF/Content/Web/mrdoob-three.js-4862f5f/utils/servers/simplehttpserver.js@ 28897

Last change on this file since 28897 was 28897, checked in by davidb, 10 years ago

GUI front-end to server base plus web page content

File size: 2.4 KB
Line 
1/**
2 * a barebones HTTP server in JS
3 * to serve three.js easily
4 *
5 * @author zz85 https://github.com/zz85
6 *
7 * Usage: node simplehttpserver.js <port number>
8 *
9 * do not use in production servers
10 * and try
11 * npm install http-server -g
12 * instead.
13 */
14
15var port = 8000,
16 http = require('http'),
17 urlParser = require('url'),
18 fs = require('fs'),
19 path = require('path'),
20 currentDir = process.cwd();
21
22
23port = process.argv[2] ? parseInt(process.argv[2], 0) : port;
24
25function handleRequest(request, response) {
26
27 var urlObject = urlParser.parse(request.url, true);
28 var pathname = decodeURIComponent(urlObject.pathname);
29
30 console.log('[' + (new Date()).toUTCString() + '] ' + '"' + request.method + ' ' + pathname + '"');
31
32 var filePath = path.join(currentDir, pathname);
33
34 fs.stat(filePath, function(err, stats) {
35
36 if (err) {
37 response.writeHead(404, {});
38 response.end('File not found!');
39 return;
40 }
41
42 if (stats.isFile()) {
43
44 fs.readFile(filePath, function(err, data) {
45
46 if (err) {
47 response.writeHead(404, {});
48 response.end('Opps. Resource not found');
49 return;
50 }
51
52 response.writeHead(200, {});
53 response.write(data);
54 response.end();
55 });
56
57 } else if (stats.isDirectory()) {
58
59 fs.readdir(filePath, function(error, files) {
60
61 if (error) {
62 response.writeHead(500, {});
63 response.end();
64 return;
65 }
66
67 var l = pathname.length;
68 if (pathname.substring(l-1)!='/') pathname += '/';
69
70 response.writeHead(200, {'Content-Type': 'text/html'});
71 response.write('<!DOCTYPE html>\n<html><head><meta charset="UTF-8"><title>' + filePath + '</title></head><body>');
72 response.write('<h1>' + filePath + '</h1>');
73 response.write('<ul style="list-style:none;font-family:courier new;">');
74 files.unshift('.', '..');
75 files.forEach(function(item) {
76
77 var urlpath = pathname + item,
78 itemStats = fs.statSync(currentDir + urlpath);
79
80 if (itemStats.isDirectory()) {
81 urlpath += '/';
82 item += '/';
83 }
84
85 response.write('<li><a href="'+ urlpath + '">' + item + '</a></li>');
86 });
87
88 response.end('</ul></body></html>');
89 });
90 }
91 });
92}
93
94http.createServer(handleRequest).listen(port);
95
96require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
97 console.log('Running at http://' + addr + ((port === 80) ? '' : ':') + port + '/');
98})
99
100console.log('Three.js server has started...');
101console.log('Base directory at ' + currentDir);
Note: See TracBrowser for help on using the repository browser.