Created
January 20, 2013 23:41
-
-
Save claytantor/4582621 to your computer and use it in GitHub Desktop.
Node.js and Phantom Screen Capture Server
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
/** | |
* Server will save rendered file to same directory and stream png | |
* to the response. | |
* | |
* npm install phantom | |
* npm install path | |
* npm install mu2 | |
* npm install fs | |
* npm install url | |
* | |
**/ | |
var http = require("http"); | |
var path = require('path'); | |
var fs = require('fs'); | |
var url = require('url'); | |
var mu = require('mu2'); | |
var mimeTypes = { | |
"html": "text/html", | |
"jpeg": "image/jpeg", | |
"jpg": "image/jpeg", | |
"png": "image/png", | |
"js": "text/javascript", | |
"css": "text/css"}; | |
function onRequest(request, response) { | |
var url_parts = url.parse(request.url, true); | |
var query = url_parts.query; | |
var phantom = require('phantom'); | |
phantom.create(function(ph) { | |
return ph.createPage(function(page) { | |
return page.open(query['url'], function(status) { | |
console.log( | |
mu.renderText( | |
'url to render: {{ url }} {{ foo }}', | |
{url:query['url'], foo:'boo'})); | |
var fname = genS4()+'.png' | |
page.render(fname, function(){ | |
var filename = path.join(process.cwd(), fname); | |
fs.exists(filename, function(exists) { | |
if(!exists) { | |
console.log("not exists: " + filename); | |
response.writeHead(200, {'Content-Type': 'text/plain'}); | |
response.write('404 Not Found\n'); | |
response.end(); | |
} | |
var mimeType = mimeTypes[path.extname(filename).split(".")[1]]; | |
response.writeHead(200, mimeType); | |
var fileStream = fs.createReadStream(filename); | |
fileStream.pipe(response); | |
}); //end path.exists | |
}); | |
}); | |
}); | |
}); | |
} | |
http.createServer(onRequest).listen(8888); | |
//----------- functions -----------// | |
function genS4() { | |
return (((1+Math.random())*0x10000)|0).toString(16).substring(1); | |
} | |
console.log("Server has started."); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment