Created
October 18, 2017 17:07
-
-
Save mk-pmb/5c955dd6c3402e40e28f34aef3d5f26f to your computer and use it in GitHub Desktop.
Angular SPA webserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* -*- coding: UTF-8, tab-width: 2 -*- */ | |
/*jslint indent: 2, maxlen: 80, continue: true, unparam: true, node: true */ | |
'use strict'; | |
/***** Angular Single Page Application Web Server ***** | |
* Example for how to enhance a simple static webserver with route | |
* exceptions. Simple = without a big framework like express. | |
* Background is to serve angular single page applications (SPA) for | |
* the HTML 5 path API, for which the same file shall be served under | |
* many different names and paths. | |
**/ | |
var spaServer, spaFilter, | |
http = require('http'), | |
pathLib = require('path'), | |
ecstatic = require('ecstatic'), | |
spaHttpPort = (+process.env.PORT || 8080), | |
moduleDir = pathLib.dirname(module.filename), | |
serveStaticFiles = ecstatic({ root: moduleDir }); | |
spaFilter = function (req, res) { | |
var reqUrl = String(req.url), | |
reqDir = reqUrl.replace(/^\/+/, '').split(/\/+/, 1)[0]; | |
console.log('I: Request for ' + JSON.stringify(reqUrl) + | |
' = directory ' + JSON.stringify(reqDir)); | |
switch (reqDir) { | |
case 'img': | |
case 'views': | |
case 'favicon.ico': | |
case 'robots.txt': | |
break; | |
default: | |
req.url = '/index.html'; | |
break; | |
} | |
serveStaticFiles(req, res); | |
}; | |
spaServer = http.createServer(); | |
spaServer.on('request', spaFilter); | |
spaServer.on('error', function reportServerError(err) { | |
console.error('E: Server error: ' + String(err)); | |
}); | |
spaServer.listen(spaHttpPort, function whenListening() { | |
// no err param: on failure, the server will emit an error event instead. | |
console.log('I: Now listening on *:' + spaHttpPort + | |
', will serve files from ' + moduleDir); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment