forked from jibeinc/juice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstaticServer.js
67 lines (57 loc) · 1.85 KB
/
staticServer.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
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const port = process.argv[2] || 8000;
/**
* Get the directory listing and convert them into links
* @param {string[]} filesArr The array of example names
* @param {string} baseDir The base directory
* @returns {string} The html item linking to the example
*/
function formatDirToHTML(filesArr, baseDir) {
filesArr = filesArr.map((currVal) => {
return `<li><a href=${path.basename(baseDir)}/${currVal}>${currVal}</a></li>`;
});
return `<ul>${filesArr.join('\n')}</ul>`;
}
http.createServer((request, response) => {
// get the path from the URL
const uri = url.parse(request.url).pathname;
// got to examples dir if not there already
if (uri === '/') {
response.writeHead(301, {Location: '/examples'});
response.end();
return;
}
// resolve current directory to the path
const filename = path.join(process.cwd(), uri);
fs.stat(filename, (error, stats) => {
if (error) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('404 Not Found\n');
response.end();
return;
}
if (stats.isDirectory()) {
fs.readdir(filename, (err, files) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(formatDirToHTML(files, filename));
response.end();
});
return;
}
fs.readFile(filename, 'binary', (err, file) => {
if (err) {
response.writeHead(500, {'Content-Type': 'text/plain'});
response.write(err + '\n');
response.end();
return;
}
response.writeHead(200);
response.write(file, 'binary');
response.end();
});
});
}).listen(parseInt(port, 10));
console.log('Static file server running at\n => http://localhost:' + port + '/\nCTRL + C to shutdown');