Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  158] [ 4]  / answers: 1 / hits: 64749  / 10 Years ago, wed, september 24, 2014, 12:00:00

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.



app.get('/api/v1/urlCheck/', function (req,res) {
var url=req.query['url'];
var request = require('request');
request.get(url, {timeout: 30000, json:false}, function (error, result) {
res.send(result.body);

});

});


Appreciate any help!


More From » node.js

 Answers
135

2021 update


Use url-exist:


import urlExist from 'url-exist';

const exists = await urlExist('https://google.com');

// Handle result
console.log(exists);

2020 update


request has now been deprecated which has brought down url-exists with it. Use url-exist instead.


const urlExist = require("url-exist");

(async () => {
const exists = await urlExist("https://google.com");
// Handle result
console.log(exists)
})();

If you (for some reason) need to use it synchronously, you can use url-exist-sync.


2019 update


Since 2017, request and callback-style functions (from url-exists) have fallen out of use.


However, there is a fix. Swap url-exists for url-exist.


So instead of using:


const urlExists = require("url-exists")

urlExists("https://google.com", (_, exists) => {
// Handle result
console.log(exists)
})

Use this:


const urlExist = require("url-exist");

(async () => {
const exists = await urlExist("https://google.com");
// Handle result
console.log(exists)
})();

Original answer (2017)


If you have access to the request package, you can try this:


const request = require("request")
const urlExists = url => new Promise((resolve, reject) => request.head(url).on("response", res => resolve(res.statusCode.toString()[0] === "2")))
urlExists("https://google.com").then(exists => console.log(exists)) // true

Most of this logic is already provided by url-exists.


[#69358] Saturday, September 20, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
declanm

Total Points: 614
Total Questions: 105
Total Answers: 97

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
;