Saying goodbye to Request: one of JavaScript’s oldest npm modules

If you’ve written any server-side JavaScript code to make an HTTP request with Node.js, you’ve likely encountered the request module.

If you are like me and have been fortunate enough to have been working with Node.js since as early as version v0.4.0 then Request is one of the first modules you’ve used to request JSON data over HTTP(S).

The request module’s HTTP GET API is fairly simple; however, if you were not around Node.js before it had a native constructor, you’d be surprised to find that request only exposes a callback and streams-based API…no promises.

const request = require('request')request('https://swapi.co/api/people/?page=1', (error, response, body) => {
console.error(`error: ${error}`)
console.error(`status code: ${response && response.statusCode}`)
console.log(body)
})

for well-formatted JSON, execute the script as follows:

If you want a promise-based API, you can use one of the alternative interfaces listed here or if you are on a version of Node.js ≥ v8.0.0, you can use the intrinsic function to convert the callback into a promise. This works with any error-first callback.

const util = require('util')
const request = util.promisify(require('request'))
request('https://swapi.co/api/people/?page=1')
.then((response) => {
console.error(`status code: ${response && response.statusCode}`)
console.log(response.body)
})
.catch((error) => {
console.error(`error: ${error}`)
})

for well-formatted JSON, execute the script as follows:

Request’s Past, Present and Future

While the request module is simple and flexible, it is going into maintenance mode to make way for modern alternatives. Many of the alternatives come out of the box with a promise-based API, some are isomorphic, and some are super light-weight.

The modern standard library

Using a third party library can be convenient; however, in many cases, simply relying on the intrinsic standard library is sufficient and Node’s standard library has been substantially revamped over the years.

Below is an example of using the native module and constructor:

const https = require('https')const gets = (url) => new Promise((resolve, reject) => {
https.get(url, (response) => {
let body = ''
response.on('data', (chunk) => body += chunk)
response.on('end', () => resolve(body))
}).on('error', reject)
})
const api = (page = 1) => {
return gets(`https://swapi.co/api/people/?page=${page}`)
}
(async () => console.log(await api()))()

for well-formatted JSON, execute the script as follows:

Closing thoughts

Thanks to Mikeal Rogers for maintaining this excellent library all these years. Furthermore, I want to commend Mikeal on a stellar explanation of why, when, and how this library will transition into maintenance mode. If you are going to transition a module into maintenance mode, you should do it like this.

Founder & CTO @ɗigitällysmµv.dev

Founder & CTO @ɗigitällysmµv.dev