node.js check if a remote URL exists

前端 未结 11 938
萌比男神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:47

    require into functions is wrong way in Node. Followed ES6 method supports all correct http statuses and of course retrieve error if you have a bad 'host' like fff.kkk

    checkUrlExists(host,cb) {
        http.request({method:'HEAD',host,port:80,path: '/'}, (r) => {
            cb(null, r.statusCode >= 200 && r.statusCode < 400 );
        }).on('error', cb).end();
    }
    

提交回复
热议问题