Created
October 11, 2013 20:45
-
-
Save mickaelandrieu/6941775 to your computer and use it in GitHub Desktop.
Use casperJs as a Webservice
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
/* from http://stackoverflow.com/questions/15852987/casperjs-passing-data-back-to-php/16489950#16489950 | |
//define ip and port to web service | |
var ip_server = '127.0.0.1:8585'; | |
//includes web server modules | |
var server = require('webserver').create(); | |
//start web server | |
var service = server.listen(ip_server, function(request, response) { | |
var links = []; | |
var casper = require('casper').create(); | |
function getLinks() { | |
var links = document.querySelectorAll('h3.r a'); | |
return Array.prototype.map.call(links, function(e) { | |
return e.getAttribute('href') | |
}); | |
} | |
casper.start('http://google.fr/', function() { | |
// search for 'casperjs' from google form | |
this.fill('form[action="/search"]', { q: 'casperjs' }, true); | |
}); | |
casper.then(function() { | |
// aggregate results for the 'casperjs' search | |
links = this.evaluate(getLinks); | |
// now search for 'phantomjs' by filling the form again | |
this.fill('form[action="/search"]', { q: 'phantomjs' }, true); | |
}); | |
casper.then(function() { | |
// aggregate results for the 'phantomjs' search | |
links = links.concat(this.evaluate(getLinks)); | |
}); | |
// | |
casper.run(function() { | |
response.statusCode = 200; | |
//sends results as JSON object | |
response.write(JSON.stringify(links, null, null)); | |
response.close(); | |
}); | |
}); | |
console.log('Server running at http://' + ip_server+'/'); |
That way, use an embedded web server module called Mongoose, PhantomJS script can start a web server. This is intended for ease of communication between PhantomJS scripts and the outside world and is not recommended for use as a general production server. There is currently a limit of 10 concurrent requests; any other requests will be queued up.
In this how I take URL from user using post call. I want pass one JSON which consists URL field?
I have just created this little project out of a personal need: https://github.com/metmajer/casperjs-as-a-service. Feel free to check it out and provide feedback, cheers!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any solution on solving the memory leak?