Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@qerub
Created December 18, 2016 00:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qerub/69fb517664c73e62188cb424d9c71a94 to your computer and use it in GitHub Desktop.
Save qerub/69fb517664c73e62188cb424d9c71a94 to your computer and use it in GitHub Desktop.
[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