DEV Community

Nikolas Evers
Nikolas Evers

Posted on • Originally published at nikol.as on

WeeklyRandom #1: sindresorhus/ua-string

Welcome to WeeklyRandom, a blog series in which I challenge myself to explore a random GitHub repository starred by me every week.

The entry for week 1 should have been published last week, but life Red Dead Redemption 2 thwarted my plans. 🤠

Never mind! Let's find out which repo I can explore this week.

🥁

node index.js vintagesucks
https://github.com/sindresorhus/ua-string

ua-string by Sindre Sorhus. This shouldn't take long. The description of the repo is as follows:

Get the user agent of a recent Chrome version to pretend to be a browser in network requests

Okay. Let's try a request to whatismybrowser.com without ua-string:

// index.js
const got = require('got');
const HTMLParser = require('fast-html-parser');

(async () => {
    try {
        got('https://developers.whatismybrowser.com/useragents/parse/?analyse-my-user-agent=yes')
        .then((res) =>
            HTMLParser.parse(res.body).querySelector('.useragent')
        )
        .then((result) =>
            console.log(result.childNodes[0].rawText)
        );
    } catch (error) {
        console.log(error.response.body);
    }
})();

Let's run it:

node index.js
got/9.2.2 (https://github.com/sindresorhus/got)

Since I used got (created by Sindre, too 👋) to make the request, the reported user agent is got.

Let's try ua-string now.

npm install ua-string

The script, now using ua-string:

const got = require('got');
const uaString = require('ua-string');
const HTMLParser = require('fast-html-parser');

(async () => {
    try {
        got('https://developers.whatismybrowser.com/useragents/parse/?analyse-my-user-agent=yes', {
            headers: {
                'user-agent': uaString
            }
        })
        .then((res) =>
            HTMLParser.parse(res.body).querySelector('.useragent')
        )
        .then((result) =>
            console.log(result.childNodes[0].rawText)
        );
    } catch (error) {
        console.log(error.response.body);
    }
})();

Here we go:

node index.js
Mozilla/5.0 (Macintosh; Intel Mac OS X 10\_13\_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36

Perfect. 🎉

You can find the complete code on GitHub at vintagesucks/weeklyrandom. Pull requests with improvements are very welcome!

Until next week, when I'll check out my next WeeklyRandom repository.

Top comments (0)