/** * Module dependencies. */ var express = require('express'), //routes = require('./routes'), phantomProxy = require('phantom-proxy'), fs = require('fs'), path = require('path'), api = require('./routes/api'); var app = module.exports = express(); // Configuration app.configure(function(){ app.set('env', 'production'); //app.use(express.logger()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes //app.get('/', routes.index); //app.get('/partials/:name', routes.partials); var appRoutes = ["/", "/home", "/contact", "/about"]; phantomProxy.create({}, function (proxy) { app.get('*', function(req, res){ var agent = req.headers["user-agent"]; //console.log(req.ip + " sended a request for URL "+req.url+" -with user-agent " + agent); var filePath = './public' + req._parsedUrl.pathname; fs.exists(filePath, function (exists) { if(exists){ res.sendfile(filePath); }else{ if(typeof agent === "string"){ if(agent.indexOf('Googlebot') === -1){ //user is not googlebot if(appRoutes.indexOf(req._parsedUrl.pathname) !== -1){ // redirect all others to the index (client app is then responsible for handling it's route) res.sendfile('./public/index.html'); }else{ res.send(404); console.log('File '+filePath+' doesnt exist'); } }else{ console.log('Request sent by crawler, will start phantom'); var page = proxy.page; page.open('http://localhost'+ req._parsedUrl.pathname , function () { page.waitForSelector('#main *', function () { console.log('main div children present'); var pageContent = null; page.evaluate(function () { return document.getElementsByTagName('html')[0].innerHTML; }, function(ret){ pageContent = ret; console.log("PhantomJS callback has been fired"); res.send(pageContent); res.end(); }); }); }); } } } }); }); process.on('exit', function() { console.log('About to exit, we shall close the phantom process.'); proxy.end(function(){}); }); }); // Start server app.listen(80, function(){ console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env); });