Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active February 28, 2018 16:17
Show Gist options
  • Save hraban/47a53acc69b052b030404389443a429a to your computer and use it in GitHub Desktop.
Save hraban/47a53acc69b052b030404389443a429a to your computer and use it in GitHub Desktop.
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
Copy link
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