node.js check if a remote URL exists

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

    my awaitable async ES6 solution, doing a HEAD request:

    // options for the http request
    let options = {
        host: 'google.de',
        //port: 80,  optional
        //path: '/'  optional
    }
    
    const http = require('http');
    
    // creating a promise (all promises a can be awaited)
    let isOk = await new Promise(resolve => {
        // trigger the request ('HEAD' or 'GET' - you should check if you get the expected result for a HEAD request first (curl))
        // then trigger the callback
        http.request({method:'HEAD', host:options.host, port:options.port, path: options.path}, result =>
            resolve(result.statusCode >= 200 && result.statusCode < 400)
        ).on('error', resolve).end();
    });
    
    // check if the result was NOT ok
    if (!isOk) 
        console.error('could not get: ' + options.host);
    else
        console.info('url exists: ' + options.host);
    

提交回复
热议问题