mirror of
https://github.com/ZZZure/ZZZ-Plugin.git
synced 2025-12-16 21:27:47 +00:00
修复无法下载资源
This commit is contained in:
parent
c71cb5a7f4
commit
bd7ad919a8
1 changed files with 20 additions and 22 deletions
|
|
@ -1,29 +1,27 @@
|
|||
import http from 'http';
|
||||
import https from 'https';
|
||||
export async function checkLatency(url) {
|
||||
let request = http;
|
||||
if (url.startsWith('https')) {
|
||||
request = https;
|
||||
import fetch from 'node-fetch';
|
||||
|
||||
export async function checkLatency(url, timeout = 5000) {
|
||||
const controller = new AbortController()
|
||||
const { signal } = controller
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout)
|
||||
|
||||
const start = Date.now()
|
||||
|
||||
try {
|
||||
await fetch(url, { signal })
|
||||
const latency = Date.now() - start
|
||||
return { url, latency }
|
||||
} catch (err) {
|
||||
logger.debug(`下载节点 ${url} 连接失败:`, err.message)
|
||||
return { url, latency: Infinity }
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
return new Promise(resolve => {
|
||||
const start = Date.now();
|
||||
request
|
||||
.get(url, res => {
|
||||
res.on('data', () => {});
|
||||
res.on('end', () => {
|
||||
const latency = Date.now() - start;
|
||||
resolve({ url, latency });
|
||||
});
|
||||
})
|
||||
.on('error', err => {
|
||||
logger.debug(`下载节点 ${url} 连接失败:`, err.message);
|
||||
resolve({ url, latency: Infinity });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export async function findLowestLatencyUrl(urls) {
|
||||
const results = await Promise.all(urls.map(checkLatency));
|
||||
const results = await Promise.allSettled(urls.map(checkLatency));
|
||||
const lowestLatencyResult = results.reduce((prev, curr) =>
|
||||
prev.latency < curr.latency ? prev : curr
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue