Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jennyknuth/faf8c1917a8c50bcfdc6 to your computer and use it in GitHub Desktop.
Save jennyknuth/faf8c1917a8c50bcfdc6 to your computer and use it in GitHub Desktop.
var http = require('http'),
fs = require('fs'),
mime = require('mime'),
colors = require('colors');
// This server is compliant with the demands of HTML5 pushstate URLs.
// See "The Reload Problem" http://www.angularonrails.com/get-html5-pushstate-working-angular-rails/
// The above article is for rails apps, but the same problem / solution apply here.
var str = "" +
" _________________\n"+
" / /|\n"+
" /________________/ |\n"+
" /| | | |\n"+
" /|/ | | | |\n"+
" /00 | * | | /\n"+
" |---- | / | hellometa | /\n"+
" \\W_W_|/ |_______________|/\n";
var str2 = "" +
" _//|\n"+
" /oo | *\n"+
" \\ww_|/\n";
var handleRequest = function (req, res) {
console.log(req.method + ' ' + req.url)
// First load the index.html file. Except for assets
// (like CSS and other public stuff), we're going to
// serve this file no matter what.
fs.readFile('./index.html', function(err, app) {
// This is expected, default behavior for a GET request
// to the root URL...
if (req.url === '/') {
res.setHeader('Content-Type', 'text/html')
res.end(app)
return
}
// If it wasn't a request for `/`, then we need to
// dynamically determine the mime tipe and serve it up.
// It's probably a CSS file or something.
res.setHeader('Content-Type', mime.lookup(req.url))
// Now we have to locate that static asset in the
// file system. If it is found, then we should just
// serve it up.
fs.readFile('.' + req.url, function (err, file) {
// If the file is NOT found, we should just return the
// application's index file. That way we can delegate the "not found"
// behavior to the client's router.
if (err) {
res.setHeader('Content-Type', 'text/html')
return res.end(app)
}
// Here ya go...
res.end(file)
})
})
}
var server = http.createServer(handleRequest)
// Heroku has a predefined PORT enviroment variable.
server.listen(process.env.PORT || 8080, function() {
console.log(str.rainbow, str2)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment