Skip to content

Instantly share code, notes, and snippets.

@rjungemann
Created May 9, 2011 07:32
Show Gist options
  • Save rjungemann/962196 to your computer and use it in GitHub Desktop.
Save rjungemann/962196 to your computer and use it in GitHub Desktop.
Run phantom and node in parallel from node, for integration testing or other purposes. Serializes a node function and runs it in phantom, and runs another node function in parallel.
require.paths.unshift(__dirname + '/../lib');
var fs = require('fs');
var exec = require('child_process').exec;
function uuid() {
return '________-____-____-____-____________'.replace(/\_/g, function(n) {
return Math.floor(Math.random() * 16).toString(16);
});
}
function functionToTempFile(f, callback) {
var path = __dirname + '/' + uuid() + '.js';
var data = '(' + f.toString() + ')(phantom);';
fs.writeFile(path, data, function(err) {
if(err) {
console.err(err);
} else {
callback(path);
}
});
}
function create(path) {
var phantom = exec('phantomjs ' + path, function(e, out, err) {
if(err) {
console.log(err);
}
if(out) {
console.log(out);
}
});
phantom.on('exit', function(code, signal) {
console.log('Phantom exiting');
process.exit();
});
return phantom;
}
function call(f, callback) {
functionToTempFile(f, function(path) {
console.log('Creating Phantom');
callback(create(path));
});
}
module.exports = {
create: create,
call: call
};
var phantom = module.exports;
/*
// example
phantom.call(function(phantom) {
// this function will be run in phantom
if(phantom.state.length === 0) {
var address = 'http://localhost';
phantom.state = Date.now().toString();
console.log('Visiting ' + address);
phantom.viewportSize = { width: 600, height: 600 };
phantom.open(address);
} else {
var elapsed = Date.now() - new Date().setTime(phantom.state);
if(phantom.loadStatus === 'success') {
console.log('Title is ' + document.title);
console.log('Loaded in ' + elapsed + 'ms');
} else {
console.log('Failed to load the address');
}
phantom.exit();
}
}, function(phantom) {
// this function will be run in node
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment