Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[TypeScript] Dependency-free Promise-based Node.js HTTP client
// Based on https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
import * as https from "https";
async function httpsExchange(requestOptions: https.RequestOptions): Promise<string> {
return new Promise<string>((resolve, reject) => {
const request = https.request(requestOptions, (response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error("Non-2xx status code: " + response.statusCode));
}
const body = new Array<Buffer | string>();
response.on("data", (chunk) => body.push(chunk));
response.on("end", () => resolve(body.join("")));
});
request.on("error", (err) => reject(err));
request.end();
});
}
// Usage:
const response = await httpsExchange({
host: "api.lifx.com",
path: "/v1/lights/id:" + LIFX_LAMP_ID,
headers: {"Authorization": "Bearer " + LIFX_TOKEN}
});
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.