node.js check if a remote URL exists

前端 未结 11 757
萌比男神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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 04:45

    Take a look at the url-exists npm package https://www.npmjs.com/package/url-exists

    Setting up:

    $ npm install url-exists
    

    Useage:

    const urlExists = require('url-exists');
    
    urlExists('https://www.google.com', function(err, exists) {
      console.log(exists); // true 
    });
    
    urlExists('https://www.fakeurl.notreal', function(err, exists) {
      console.log(exists); // false 
    });
    

    You can also promisify it to take advantage of await and async:

    const util = require('util');
    const urlExists = util.promisify(require('url-exists'));
    
    let isExists = await urlExists('https://www.google.com'); // true
    isExists = await urlExists('https://www.fakeurl.notreal'); // false
    

    Happy coding!

提交回复
热议问题