aendrew aendrew - 4 months ago 40
Javascript Question

Detecting a 301 redirect or 404 in JSDom

I'm using JSDom to scrape pages and check page existence on bunch of S3 buckets. My buckets redirect to an page on 404 that then redirects to my site's main page. While trying to load a totally non-existent domain yields a

ENOTFOUND
error, the
errors
object is empty if I get a 404.

Using JSDom, how do I detect a redirect or a 404?

Answer

You could use request and get the statusCode. them pass the HTML fragment to JSDOM like so:

var jsdom = require("jsdom");
var request = require('request'); 
request(url, function (err, response, body) {
    if (!err && response.statusCode == 200) {
        jsdom.env({
            html:body,
            scripts: ["http://code.jquery.com/jquery.js"],
            done: JS_DOM_FUNCTION()
        });
    }
    else{
    //You can handle any other status here

    }
});