Menu

HTTP GET Requests with Node

This series of posts catalogs basic functions in Node via the built-in APIs. There are many libraries that provide syntactic sugar over these functions. However, it's a good exercise to understand how to do them manual. As serverless architectures increase in popularity, for performance reasons it's important to reduce dependencies and size of the deployment packages.

I'm starting this series with a post on making HTTP GET requests since it was one of the recent changes I made to a serverless application to improve performance. This functionality is found in https://nodejs.org/api/http.html

GET Request

The simplest request to make is a GET request. This example converts the request into a Promise based function using the standard Promise class.

This pattern is suitable for small requests (such as web page fetches) due to how it keeps all buffer parts in memory. This pattern would not be suitable for large request where you would want to return the result object directly and stream it to disk or some other output location.

The final piece is actually initiating the request. The request function takes two arguments options and callback and returns an instance of ClientRequest.

With this instance, it will listen for an error event and reject the promise if encountered. Otherwise it will finalize the request by calling end.