jay.jivani
jay.jivani

Reputation: 1574

Collect all redirected URL of Origin URL using NodeJS

I want to retrieve a list of urls that are redirected from Origin URL X and it may have many redirected URLs but i want all list of it.

For example:

http://www.example.com/origin-url

It will redirect to

http://www.example.com/first-redirect

Again it will redirect to

http://www.example.com/second-redicect

And finally it goes to this

http://www.example.com/final-url

So what i want is list of all this URLs using NodeJs or Express

 http://www.example.com/origin-url -->> http://www.example.com/first-redirect
 -->> http://www.example.com/second-redicect -->> http://www.example.com/final-url

Give me suggestion for this and which node module should i have to use to achieve this.

Thanks in advance.

Upvotes: 3

Views: 822

Answers (1)

Tolsee
Tolsee

Reputation: 1705

You can use the http module of NodeJS. You will need to check the statusCode, which for redirect is between 300-400. Please look at the below code.

    var http = require('http')


    function listAllRedirectURL(path) {
      var reqPath = path;
      return new Promise((resolve, reject) => {
        var redirectArr = [];

        function get(reqPath, cb){
            http.get({
              hostname: 'localhost',
              port: 3000,
              path: reqPath,
              agent: false  // create a new agent just for this one request
            }, (res) => {
              cb(res)
            }); 
        }

        function callback(res) {
            if (res.headers.hasOwnProperty('location') && res.statusCode >= 300 && res.statusCode < 400) {
               console.log(res.headers.location);
               redirectArr.push(res.headers.location);
               reqPath = (res.headers.location);
               get(reqPath, callback);
            } else {
              resolve(redirectArr);
            }
        }

        get(reqPath, callback);
      })
    }

    listAllRedirectURL('/');

Upvotes: 3

Related Questions