node.js check if a remote URL exists

前端 未结 11 937
萌比男神i
萌比男神i 2021-02-05 04:28

How do I check to see if a URL exists without pulling it down? I use the following code, but it downloads the whole file. I just need to check that it exists.

ap         


        
11条回答
  •  天命终不由人
    2021-02-05 04:49

    Thanks! Here it is, encapsulated in a function (updated on 5/30/17 with the require outside):

        var http = require('http'),
             url = require('url');
    
        exports.checkUrlExists = function (Url, callback) {
            var options = {
                method: 'HEAD',
                host: url.parse(Url).host,
                port: 80,
                path: url.parse(Url).pathname
            };
            var req = http.request(options, function (r) {
                callback( r.statusCode== 200);});
            req.end();
        }
    

    It's very quick (I get about 50 ms, but it will depend on your connection and the server speed). Note that it's also quite basic, i.e. it won't handle redirects very well...

提交回复
热议问题