-
Notifications
You must be signed in to change notification settings - Fork 5.8k
API Reference WebServer
This is a living document. As the codebase is updated, we hope to keep this document updated as well. Unless otherwise stated, this document currently applies to the latest PhantomJS release: PhantomJS 1.8.0
Note: This page serves as a reference. To learn step-by-step on how to use PhantomJS, please refer to the Quick Start guide.
## Module: WebServer ## **Stability:** _EXPERIMENTAL_ **Introduced:** PhantomJS 1.4 Using an embedded web server module called [Mongoose](http://code.google.com/p/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.Here is a simple example that always gives the same response regardless of the request:
var server = require('webserver').create();
var service = server.listen(8080, function(request, response) {
response.statusCode = 200;
response.write('<html><body>Hello!</body></html>');
response.close();
});
If you want to bind to specify address, just use ipaddress:port
instead of port
.
Example:
var server = require('webserver').create();
var service = server.listen('127.0.0.1:8080', function(request, response) {
response.statusCode = 200;
response.write('<html><body>Hello!</body></html>');
response.close();
});
The value returned by server.listen()
is a boolean: true if the server is launched.
An optional object opts
can be passed between the IP/port and the callback:
var service = server.listen(8080, { 'keepAlive': true }, function(request, response) { ... });
Currently, the only supported option is keepAlive
. If set to true
, the webserver will support keep-alive connections. Note: servers that have keep-alive enabled must set a proper Content-Length header in their responses, otherwise clients will not know when the response is finished; additionally, response.close()
must be called. See examples/serverkeepalive.js for more information.
The server
object contains these functions:
-
close()
: close the server -
port
: the port on which the server listen requests (readonly)