mirror of
https://github.com/ZZZure/ZZZ-Plugin.git
synced 2025-12-18 06:07:34 +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 fetch from 'node-fetch';
|
||||||
import https from 'https';
|
|
||||||
export async function checkLatency(url) {
|
export async function checkLatency(url, timeout = 5000) {
|
||||||
let request = http;
|
const controller = new AbortController()
|
||||||
if (url.startsWith('https')) {
|
const { signal } = controller
|
||||||
request = https;
|
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) {
|
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) =>
|
const lowestLatencyResult = results.reduce((prev, curr) =>
|
||||||
prev.latency < curr.latency ? prev : curr
|
prev.latency < curr.latency ? prev : curr
|
||||||
);
|
);
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue