ssn/src/getUrlContents.ts

36 lines
1 KiB
TypeScript
Raw Normal View History

2018-06-21 15:44:13 +02:00
import * as http from 'http';
export default function getUrlContents({ host, path }: {host: string, path: string}): Promise<Buffer> {
return new Promise((resolve, reject) => {
const request = http.request({
family: 4,
host,
path,
}, (response) => {
if (response.statusCode !== 200) {
return reject(`Expected status code 200 but received ${response.statusCode}`);
}
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
});
request.on('error', (e) => {
reject(e);
});
request.end();
2018-06-21 15:44:13 +02:00
});
}