puppeteer/phantom_shim/WebServer.js
Andrey Lushnikov 79ceb0c439 Consolidate phantom shim code in the phantom-shim folder
This patch:
- renames phantomjs folder into phantom_shim
- moves bin/puppeteer into a phantom_shim/runner.js and
  merges the file with phantomjs/index.js
- removes "bin" field from the package.json - it is confusing
  to have phantom shim installable
2017-06-14 02:27:19 -07:00

84 lines
2.6 KiB
JavaScript

/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var http = require('http');
var await = require('./utilities').await;
class WebServer {
constructor() {
this._server = http.createServer();
this.objectName = 'WebServer';
this.listenOnPort = this.listen;
this.newRequest = function(req, res) { };
Object.defineProperty(this, 'port', {
get: () => {
if (!this._server.listening)
return '';
return this._server.address().port + '';
},
enumerable: true,
configurable: false
});
}
close() {
this._server.close();
}
/**
* @param {nubmer} port
* @return {boolean}
*/
listen(port, callback) {
if (this._server.listening)
return false;
this.newRequest = callback;
this._server.listen(port);
var errorPromise = new Promise(x => this._server.once('error', x));
var successPromise = new Promise(x => this._server.once('listening', x));
await(Promise.race([errorPromise, successPromise]));
if (!this._server.listening)
return false;
this._server.on('request', (req, res) => {
res.close = res.end.bind(res);
var headers = res.getHeaders();
res.headers = [];
for (var key in headers) {
res.headers.push({
name: key,
value: headers[key]
});
}
res.header = res.getHeader;
res.setHeaders = headers => {
for (var key in headers)
res.setHeader(key, headers[key]);
};
Object.defineProperty(res, 'statusCode', {
enumerable: true,
configurable: true,
writable: true,
value: res.statusCode
});
this.newRequest.call(null, req, res);
});
return true;
}
}
module.exports = WebServer;