Search code examples
node.jshttprequest

How to get max-age value from cache-control header using request in Nodejs?


I am using request to request a page with the following code:

request(url, { json: true }, (err, res, body) => {
    if (err) {
        return null
    } else {
        console.log("res", res.headers["cache-control"]);
    }
})

I can get the cache-control header this way. But how do I get the max-age value which is in cache-control header, like cache-control: public, max-age=20140, must-revalidate, no-transform ? Is there any shorthand or do I have to do string manipulations?


Solution

  • There is no shorthand - headers are simply key/value pairs and there are no standard libraries in JS to parse structured header values.

    You could just use a regex to pull out the number:

    const headers = {
      'cache-control': 'public, max-age=20140, must-revalidate, no-transform'
    }
    
    const matches = headers['cache-control']?.match(/max-age=(\d+)/)
    
    const maxAge = matches ? parseInt(matches[1], 10) : -1
    
    console.log(maxAge)