node.js check if a remote URL exists

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

    Using the other responses as reference, here's a promisified version which also works with https uris (for node 6+):

    const http = require('http');
    const https = require('https');
    const url = require('url');
    
    const request = (opts = {}, cb) => {
      const requester = opts.protocol === 'https:' ? https : http;
      return requester.request(opts, cb);
    };
    
    module.exports = target => new Promise((resolve, reject) => {
      let uri;
    
      try {
        uri = url.parse(target);
      } catch (err) {
        reject(new Error(`Invalid url ${target}`));
      }
    
      const options = {
        method: 'HEAD',
        host: uri.host,
        protocol: uri.protocol,
        port: uri.port,
        path: uri.path,
        timeout: 5 * 1000,
      };
    
      const req = request(options, (res) => {
        const { statusCode } = res;
    
        if (statusCode >= 200 && statusCode < 300) {
          resolve(target);
        } else {
          reject(new Error(`Url ${target} not found.`));
        }
      });
    
      req.on('error', reject);
    
      req.end();
    });
    

    It can be used like this:

    const urlExists = require('./url-exists')
    
    urlExists('https://www.google.com')
      .then(() => {
        console.log('Google exists!');
      })
      .catch(() => {
        console.error('Invalid url :(');
      });
    

提交回复
热议问题