2018-06-21 15:44:13 +02:00
|
|
|
import * as http from 'http';
|
|
|
|
|
2018-06-21 21:52:56 +02:00
|
|
|
export default function getUrlContents({ host, path }: {host: string, path: string}): Promise<Buffer> {
|
2018-06-21 21:26:29 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const request = http.request({
|
|
|
|
family: 4,
|
2018-06-21 21:52:56 +02:00
|
|
|
host,
|
2018-06-21 21:26:29 +02:00
|
|
|
path,
|
|
|
|
}, (response) => {
|
|
|
|
if (response.statusCode !== 200) {
|
|
|
|
return reject(`Expected status code 200 but received ${response.statusCode}`);
|
2018-06-21 20:05:57 +02:00
|
|
|
}
|
2018-06-21 21:26:29 +02:00
|
|
|
const headerLength = Number(response.headers['content-length']);
|
|
|
|
|
|
|
|
const chunkList: Buffer[] = [];
|
|
|
|
let totalLength = 0;
|
|
|
|
response.on('data', (chunk: Buffer) => {
|
|
|
|
chunkList.push(chunk);
|
|
|
|
totalLength += chunk.length;
|
|
|
|
});
|
|
|
|
response.on('end', () => {
|
|
|
|
if (totalLength !== headerLength) {
|
|
|
|
return reject(`Expected length ${headerLength} but received ${totalLength}`);
|
|
|
|
}
|
|
|
|
const fileContents = Buffer.concat(chunkList, totalLength);
|
|
|
|
resolve(fileContents);
|
|
|
|
});
|
2018-06-21 15:44:13 +02:00
|
|
|
});
|
|
|
|
|
2018-06-21 21:26:29 +02:00
|
|
|
request.on('error', (e) => {
|
|
|
|
reject(e);
|
|
|
|
});
|
|
|
|
request.end();
|
2018-06-21 15:44:13 +02:00
|
|
|
});
|
2018-06-21 21:26:29 +02:00
|
|
|
}
|