Skip to content

Instantly share code, notes, and snippets.

@hraban hraban/get.ts
Last active Feb 28, 2018

Embed
What would you like to do?
Autonomous http(s) request lib for node, inspired by Tomas Dvorak
// copied from:
// https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
// Licensed under: Attribution 4.0 International (CC BY 4.0)
// https://creativecommons.org/licenses/by/4.0/
// (note: there's some funky url parsing business which I didn't fully test; caveat emptor)
import * as http from "http";
import * as https from "https";
import * as url from "url";
async function getString(u: string | url.URL, headers?: http.OutgoingHttpHeaders): Promise<string> {
return new Promise<string>((resolve, reject) => {
// select http or https module, depending on reqested url
let isHttps: boolean;
const options: http.RequestOptions = {
headers,
}
if (typeof u === 'string') {
Object.assign(options, url.parse(u));
isHttps = u.startsWith('https');
} else {
Object.assign(options, u);
isHttps = u.protocol === 'https:';
}
const lib = <typeof http>(isHttps ? https : http);
const request = lib.get(options, (response) => {
if (!response.statusCode || response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
const body: (string|Buffer)[] = [];
response.on('data', (chunk) => body.push(chunk));
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
});
};
async function getJSON(u: string | url.URL, headers?: http.OutgoingHttpHeaders): Promise<object> {
const body = await getString(u, headers)
try {
return JSON.parse(body);
} catch (e) {
console.error(body);
throw e;
}
}
export {
getString as string,
getJSON as JSON,
}
@hraban

This comment has been minimized.

Copy link
Owner Author

hraban commented Feb 28, 2018

This doesn't work for non-default ports, and I don't know how to make it work. It's a disaster, tbh. I now understand why the 3rd party "request" lib has 98230198 dependencies.

What a travesty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.