Last active
December 17, 2015 16:19
-
-
Save starstuck/5637829 to your computer and use it in GitHub Desktop.
Simple server expanding esi:include tags from local html files. Very usefull to test your static pages before uploading to Akamai. Written in node.js.
This file contains hidden or 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
| /** | |
| * Simple server expanding esi:include tags from local html files. | |
| * Very usefull to test your static pages before uploading to Akamai. | |
| * | |
| * $ npm install express | |
| * | |
| * Now you are ready to run preview server: | |
| * | |
| * $ node esi-server.js | |
| * | |
| * @author Tomasz Szarstuk <szarsti at gmail> | |
| * @license MIT | |
| */ | |
| var express = require('express'), | |
| fs = require('fs'), | |
| url = require('url'), | |
| http = require('http'), | |
| app = express(); | |
| function handleEsiFile(req, res) { | |
| var name = req.params[0]; | |
| fs.readFile(__dirname + '/html/' + name, 'utf-8', function(err, data) { | |
| if (err) { | |
| console.log('Error reading file: ', err); | |
| res.send(500, 'Error reading file: ', err.message); | |
| return; | |
| } | |
| var re = /<esi:include[^>]*src="([^"]*)"[^>]*>/g, | |
| html = data; | |
| res.type('html'); | |
| function expand(idx) { | |
| var m = re.exec(html), | |
| lastIndex, | |
| u; | |
| if (m) { | |
| lastIndex = re.lastIndex; | |
| res.write(html.slice(idx, lastIndex - m[0].length)); | |
| u = url.parse(m[1]); | |
| http.get({ | |
| host: u.host, | |
| port: u.port || 80, | |
| path: u.path | |
| }, function(response) { | |
| response | |
| .on('data', function(chunk) { | |
| res.write(chunk); | |
| }) | |
| .on('end', function () { | |
| expand(lastIndex); | |
| }); | |
| }).on('error', function (err) { | |
| console.log('Error expanding esi:include src: ' + err); | |
| }); | |
| } else { | |
| res.write(html.slice(idx)); | |
| res.end(); | |
| } | |
| } | |
| expand(0); | |
| }); | |
| } | |
| app.configure(function () { | |
| app.get(/^\/([\w\.-]+\.html)/, handleEsiFile); | |
| app.use("/static/", express.static(__dirname + '/static/')); | |
| }); | |
| app.listen(3001); | |
| console.log('ESI pages preview running on http://localhost:3001/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment