Skip to content

Instantly share code, notes, and snippets.

@yuqianma
Created March 30, 2017 19:18
Show Gist options
  • Save yuqianma/345c118e847fce866978aed003b67a44 to your computer and use it in GitHub Desktop.
Save yuqianma/345c118e847fce866978aed003b67a44 to your computer and use it in GitHub Desktop.
phantomjs child process exp
var system = require('system'),
fs = require('fs'),
process = require("child_process");
var children = {};
var port = system.args[1];
var isParent = system.args[2];
console.log('[process] port:', port);
startServer('127.0.0.1', system.args[1]);
if (!isParent) {
initPage();
}
function initPage() {
var page = require('webpage').create();
page.onConsoleMessage = function (msg, lineNum, sourceId) {
console.log(msg, lineNum, sourceId);
};
page.evaluate(function() {
var duration = 1000 * 10;
var initTime = new Date();
var i = 0;
console.log('page init while', initTime);
while (new Date() - initTime < duration) {
++i;
}
console.log('page exit while', new Date());
});
return page;
}
function spawnProcess (port) {
if (!port || children[port]) {
return
}
var spawn = process.spawn
var child = spawn("../phantomjs-2.1.1-macosx/bin/phantomjs", ["process.js", port])
child.stdout.on("data", function (data) {
console.log('[' + port + ",STDOUT]", data)
})
child.stderr.on("data", function (data) {
console.log('[' + port + ",STDERR]", data)
})
child.on("exit", function (code) {
killProcess(port);
console.log('[' + port + ",EXIT]", code)
})
//child.kill("SIGKILL")
children[port] = child;
}
function killProcess (port) {
if (!(port && children[port])) {
return
}
children[port].kill("SIGKILL");
children[port] = null;
delete children[port];
}
function startServer (host, port) {
var server = require('webserver').create();
server.listen(host ? host + ':' + port : parseInt(port, 10),
function (request, response) {
var query = getQuery(request.url);
var portToKill;
if (portToKill = query['kill']) {
killProcess(portToKill);
}
var portToSpawn;
if (portToSpawn = query['spawn']) {
spawnProcess(portToSpawn)
}
var childrenStr = '';
if ('tell' in query) {
childrenStr = Object.keys(children).join();
}
reply(childrenStr);
if ('exit' in query) {
phantom.exit();
}
// helper
function reply(result) {
if (!response) {
return;
}
console.log(port + ' res: ', result)
response.statusCode = 200;
response.write(result);
response.close();
}
function onError(msg, e) {
msg = 'Failed rendering: \n';
if (e) { msg += e; }
response.statusCode = 500;
response.write(msg);
response.close();
}
}); // end server.listen
console.log('PhantomJS server start pid:' + system.pid + ', port:' + port);
}
function getQuery(url) {
var matches = url.match(/([^?=&]+)(=([^&]*))?/g);
matches.shift();
return matches.reduce(function(a, b){var item = b.split('='); a[item[0]]=item[1] ; return a}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment