Skip to content

Instantly share code, notes, and snippets.

@claytantor
Created January 20, 2013 23:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claytantor/4582621 to your computer and use it in GitHub Desktop.
Save claytantor/4582621 to your computer and use it in GitHub Desktop.
Node.js and Phantom Screen Capture Server
/**
* 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