2021 年更新
使用url-exist:
import urlExist from 'url-exist';
const exists = await urlExist('https://google.com');
// Handle result
console.log(exists);
2020 年更新
request 现在已被弃用,这导致url-exists 随之失效。请改用url-exist。
const urlExist = require("url-exist");
(async () => {
const exists = await urlExist("https://google.com");
// Handle result
console.log(exists)
})();
如果你(由于某种原因)需要同步使用,可以使用url-exist-sync。
2019 年更新
自 2017 年以来,request 和回调样式函数(来自 url-exists)已不再使用。
但是,有一个修复方法。将url-exists 换成url-exist。
所以不要使用:
const urlExists = require("url-exists")
urlExists("https://google.com", (_, exists) => {
// Handle result
console.log(exists)
})
使用这个:
const urlExist = require("url-exist");
(async () => {
const exists = await urlExist("https://google.com");
// Handle result
console.log(exists)
})();
原始答案(2017 年)
如果你可以访问request 包,你可以试试这个:
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
大部分逻辑已经由url-exists提供。