1

I don't want to actually follow the re-direct as seen here, I simply want to detect a redirect.

Here is my current code. Please note I want to simply detect a redirect and not do anything with it. The code works fine but downloads gibberish on a redirect.

I don't want to use any external modules. I believe there is a thing called headers that might come in use.

const https = require('https');
const fs = require('fs');

function download(entry, destination, callback) {
  const writeStream = fs.createWriteStream(destination);
  const request = https.get(entry, (response) => {
    response.pipe(writeStream);
  }).on('error', (error) => {
    console.log('DEBUG:', error);
  });
}

A good example of a redirect is here:

https://www.imdb.com/favicon.ico

user17791008
  • 247
  • 2
  • 12

2 Answers2

0

You can do something like this

if (
    response.statusCode >= 300 &&
    response.statusCode < 400 &&
    'location' in response.headers
  ) {
    console.log('redirect detected');
  }

full code:

const https = require('https');
const fs = require('fs');

function download(entry, destination, callback) {
  const writeStream = fs.createWriteStream(destination);
  const request = https.get(entry, (response) => {
    if (
      response.statusCode >= 300 &&
      response.statusCode < 400 &&
      'location' in response.headers
    ) {
      console.log('redirect detected');
    }

    response.pipe(writeStream);
  }).on('error', (error) => {
    console.log('DEBUG:', error);
  });
}

According to https://github.com/request/request/blob/86b99b671a3c86f4f963a6c67047343fd8edae8f/request.js#L762

valerii15298
  • 737
  • 4
  • 15
0

If you look at your response.headers, you will notice that any time there is a redirect, that a property called location is populated.

So to check for a redirect, simply do

if(response.headers.location) {
  // redirect detected
}
favor
  • 355
  • 2
  • 13