node.js check if a remote URL exists

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

    Currently request module is being deprecated as @schlicki pointed out. One of the alternatives in the link he posted is got:

    const got = require('got');
    
    (async () => {
        try {
            const response = await got('https://www.nodesource.com/');
            console.log(response.body);
            //=> ' ...'
        } catch (error) {
            console.log(error.response.body);
            //=> 'Internal server error ...'
        }
    })();
    

    But with this method, you will get the whole HTML page in the reponse.body. In addition got may have many more functionalities you may not need. That's I wanted to add another alternative I found to the list. As I was using the portscanner library, I could use it for the same aim without downloading the content of the website. You may need to use the 443 port as well if the website works with https

    var portscanner = require('portscanner')
    
    // Checks the status of a single port
    portscanner.checkPortStatus(80, 'www.google.es', function(error, status) {
        // Status is 'open' if currently in use or 'closed' if available
        console.log(status)
    })
    

    Anyway, the most close approach is url-exist module as @Richie Bendall explains in his post. I just wanted to add some other alternative

提交回复
热议问题