/* original : https://gist.github.com/BinaryMuse/2378993 Changes : -Shares an instance of phantomJS for all requests instead of creating a new one for each -Sends the created file as a response -Uses good old JavaScript -Coffee version below */ var phantom = require('phantom'), _ = require('underscore'),//if you dont want underscore, do a foreach instead of _.each phantomInstance = false, phantomCallbacks = []; console.log("Opening a new phantomJS instance"); phantom.create(function(ph) { console.log("PhantomJS loaded"); phantomInstance = ph; _.each(phantomCallbacks, function(cb){ cb(); }); }); exports.takeSnapshot = function(folder, filename, url, res) { var DEST_ROOT = "../../"; var filepath = folder + "/" + filename; var previewPath = DEST_ROOT + filepath; function snapShot(){ return phantomInstance.createPage(function(page) { page.set('viewportSize', { width: 640, height: 800 }); page.set('clipRect', { top: 0, left: 0, width: 640, height: 800 }); console.log("Opening " + url + " ..."); return page.open(url, function(status) { console.log("Rendering screenshot ..."); return setTimeout((function() { return page.render(previewPath, function() { page.close(); setTimeout(function(){ res.sendfile(filepath, {root: __dirname+DEST_ROOT}); }, 10); }); }), 500); }); }); } if(phantomInstance){ snapShot(); } else{ phantomCallbacks.push(snapShot); } }