NodeJS, bypass linux hosts file

Viewed 4002

Is there a way in NodeJS to bypass linux's /etc/hosts file?

For example, if I have an entry in my hosts file like: 127.0.0.1 example.com

How would I access the 'real' example.com from NodeJS?

I don't want to temporarily modify /etc/hosts to do this, as it can bring about some problems and is not a clean solution.

Thanks in advance!

2 Answers

Based on @supersam654 and this: my solution (full example) with .get request (igrnore hosts with all requests):

const dns = require("dns");
const url = require("url");

const req = (urlString, cb) => {
    const parsedUrl = url.parse(urlString);
    const hostname = parsedUrl.hostname;

    dns.resolve4(hostname, function(err, res) {
        if (err) throw err;
        console.log(`A real IP address of ${hostname} is: ${res[0]}`);
        const newUrl = urlString.replace(`${parsedUrl.protocol}//${hostname}`, `${parsedUrl.protocol}//${res[0]}`);

        https
            .get(
                newUrl,
                {
                    headers: { host: hostname },
                    servername: hostname
                },
                resp => {
                    let data = "";

                    // A chunk of data
                    resp.on("data", chunk => {
                        data += chunk;
                    });

                    // The whole response has been received. Print out the result.
                    resp.on("end", () => {
                        cb(data);
                    });
                }
            )
            .on("error", err => {
                console.log("Error request " + url + ": " + err.message);
            });
    });
};

// Example
req("https://google.com/", data => console.log(data));
Related