-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.js
87 lines (66 loc) · 2.48 KB
/
webserver.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
var express = require('express');
var fs = require('fs');
var path = require('path');
var tessel = require('tessel');
var app = express();
var mount = '/mnt/sda1'; // usb drive in Tessel; top USB slot
// var mount = '/Volumes/USB\ DISK'; // local machine's USB drive
var port = 8080;
// Respond to the request with our index.html page
function sendFile (filename, request, response) {
if (filename.includes('.html')) {
response.writeHead(200, {"Content-Type": "text/html"});
} else if (filename.includes('.js')) {
response.writeHead(200, {"Content-Type": "text/javascript"});
} else if (filename.includes('.css')) {
response.writeHead(200, {"Content-Type": "text/css"});
}
console.log('about to send', filename);
fs.readFile(path.join(__dirname, filename), function (err, content) {
if (err) { throw new Error(err); }
response.end(content);
});
}
app.get('/', function (request, response) {
sendFile('/index.html', request, response);
});
app.get('/frontend.js', function(request, response) {
sendFile('/frontend.js', request, response);
});
app.get('/cutestrap.min.css', function(request, response) {
sendFile('/cutestrap.min.css', request, response);
});
// Make available the files in the USB drive inserted into the top port
app.use(express.static(mount));
// Endpoint for initial AJAX request from index.html
app.get('/dir', function (request, response) {
fs.readdir(mount, function(err, files) {
if (err) {throw new Error(err); }
console.log('working on that ajax');
response.writeHead(200, {"Content-Type": "application/json"});
files = files.filter(function(f) {
return f[0] !== '.';
});
response.end(JSON.stringify({files: files}));
});
});
// Add routes for files that are, in reality, *directories*!
app.get(/[^A-z0-9\s]/, function (request, response) {
// todo: improve handling of the favicon.ico file
if (request.url.includes('favicon')) {return; }
var newDir = request.url.replace(/%20/g, ' ');
fs.readdir(path.join(mount, newDir), function(err, files) {
if (err) {throw new Error(err); }
response.writeHead(200, {"Content-Type": "application/json"});
// Does not return hidden files
files = files.filter(function(f) {
return f[0] !== '.';
});
// might want to serve another template-like HTML page
// and send this JSON that way
response.end(JSON.stringify({files: files}));
});
});
app.listen(port, function() {
console.log('Server running at http://192.168.1.101:' + port);
});