Skip to content

Commit

Permalink
Replace http-server with custom node server since http-server does no…
Browse files Browse the repository at this point in the history
…t server wasm mime-type for Firefox
  • Loading branch information
allen-garvey committed Jul 25, 2018
1 parent 3f1a823 commit 5cd5baf
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 4 deletions.
6 changes: 2 additions & 4 deletions package.json
Expand Up @@ -5,11 +5,9 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "http-server public_html -c-1 -p 3000"
"start": "node static_server.js 3000 public_html"
},
"author": "Allen Garvey",
"license": "MIT",
"devDependencies": {
"http-server": "^0.11.1"
}
"devDependencies": {}
}
70 changes: 70 additions & 0 deletions static_server.js
@@ -0,0 +1,70 @@
/**
* Based on: https://gist.github.com/aolde/8104861
* which is a fork of: https://gist.github.com/ryanflorence/701407
* Can't use vanilla http-server, since it doesn't use wasm mime-type, which is required for this to work in FireFox
*/

function error404(response){
response.writeHead(404, { "Content-Type": "text/plain" });
response.write("404 Not Found\n");
response.end();
}

var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 3000,
mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css",
"wasm": "application/wasm",
};
var publicRoot = process.cwd();
if(process.argv[3]){
publicRoot = path.join(publicRoot, process.argv[3]);
}

http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname;
var filename = path.join(publicRoot, uri);
//to prevent directory traversal using ../
if(!filename.startsWith(publicRoot)){
return error404(response);
}

fs.exists(filename, function(exists) {
if(!exists) {
return error404(response);
}

if (fs.statSync(filename).isDirectory())
filename += '/index.html';

fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}

var mimeType = mimeTypes[filename.split('.').pop()];

if (!mimeType) {
mimeType = 'text/plain';
}

response.writeHead(200, { "Content-Type": mimeType });
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));

console.log(`Static file server serving files from ${publicRoot} running at http://localhost:${port}/\nCTRL + C to shutdown`);

0 comments on commit 5cd5baf

Please sign in to comment.