Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Forked from ryanflorence/static_server.js
Last active November 24, 2015 00:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kentcdodds/9f1b4d80140ba749d937 to your computer and use it in GitHub Desktop.
Save kentcdodds/9f1b4d80140ba749d937 to your computer and use it in GitHub Desktop.
Angular Static Server - Serves up static files. If the request doesn't match one, it'll send the hash version and lets Angular leverage html5Mode. Haven't tested it with Ember or others, but I imagine they'd work just as well. Thanks to rpflorence for the original version.
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var base = path.join(process.cwd(), process.argv[2] || '');
var port = process.argv[3] || 8888;
var extensionRegex = /\.([0-9a-z]+)(?:[\?#]|$)/i;
var contentTypeMap = {
html: 'text/html',
js: 'application/javascript',
css: 'text/css',
png: 'image/png',
jpg: 'image/jpeg'
};
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
var filename = path.join(base, uri);
fs.exists(filename, function(exists) {
if(!exists) {
// instead of a 404, redirect to hash version and angular will take care of the rest
var hashVersion = '/#' + uri;
console.log('could not find:', filename, ' --- ', 'redirecting to:', hashVersion);
response.writeHead(302, { Location: hashVersion });
response.end();
return;
}
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 extension = filename.match(extensionRegex)[1];
response.writeHead(200, {'Content-Type': contentTypeMap[extension] || 'text/plain'});
response.write(file, 'binary');
response.end();
});
});
}).listen(parseInt(port, 10));
console.log('Serving up \n => ' + base + '\nRunning at\n => http://localhost:' + port + '/\nCTRL + C to shutdown');
# serve up current directory on 8888
node server.js
# now on 8080
node server.js / 8080
# now serve up child directory
node server.js app/
# finally serve up child directory on 8080
node server.js app/ 8080
@kentcdodds
Copy link
Author

Angular Static Server: Added functionality for SPAs with the html5 history api. Now instead of a 404, it will redirect to the hash version of the request. Also allowing you to specify a child directory for the base if you wanna.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment