puppeteer/phantom_shim/WebServer.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-05-11 07:06:41 +00:00
/**
* 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.
*/
let http = require('http');
let await = require('./utilities').await;
2017-05-11 07:06:41 +00:00
class WebServer {
2017-06-21 20:51:06 +00:00
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
});
}
2017-05-11 07:06:41 +00:00
2017-06-21 20:51:06 +00:00
close() {
this._server.close();
}
2017-05-11 07:06:41 +00:00
2017-06-21 20:51:06 +00:00
/**
* @param {nubmer} port
* @return {boolean}
*/
2017-06-21 20:51:06 +00:00
listen(port, callback) {
if (this._server.listening)
return false;
this.newRequest = callback;
this._server.listen(port);
let errorPromise = new Promise(x => this._server.once('error', x));
let successPromise = new Promise(x => this._server.once('listening', x));
2017-06-21 20:51:06 +00:00
await(Promise.race([errorPromise, successPromise]));
if (!this._server.listening)
return false;
2017-05-11 07:06:41 +00:00
2017-06-21 20:51:06 +00:00
this._server.on('request', (req, res) => {
res.close = res.end.bind(res);
let headers = res.getHeaders();
2017-06-21 20:51:06 +00:00
res.headers = [];
for (let key in headers) {
2017-06-21 20:51:06 +00:00
res.headers.push({
name: key,
value: headers[key]
2017-05-11 07:06:41 +00:00
});
2017-06-21 20:51:06 +00:00
}
res.header = res.getHeader;
res.setHeaders = headers => {
for (let key in headers)
2017-06-21 20:51:06 +00:00
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;
}
2017-05-11 07:06:41 +00:00
}
module.exports = WebServer;