speed.cloudflare.com是否有非CLI的JavaScript测速API可用于Node.js应用?
实现基于Cloudflare测速的Node.js客户端按钮并上报Google Sheets
直接使用Cloudflare公开的测速端点,无需依赖第三方npm包,即可实现和官方控制台一致精度的测速,再结合Node.js后端完成Google Sheets上报。
步骤1:前端实现测速按钮与Cloudflare测速逻辑
前端通过浏览器原生API发起请求,模拟Cloudflare的测速流程,实现下载、上传、延迟测量:
// 测速核心逻辑 async function runCloudflareSpeedTest() { const results = { download: 0, upload: 0, ping: 0, timestamp: new Date().toISOString() }; // 测量延迟(Ping) const pingStart = performance.now(); await fetch('https://cloudflare.com/cdn-cgi/trace'); results.ping = Math.round(performance.now() - pingStart); // 测量下载速度(10MB资源) const downloadSize = 10 * 1024 * 1024; const downloadStart = performance.now(); const downloadRes = await fetch(`https://speed.cloudflare.com/__down?bytes=${downloadSize}`); await downloadRes.arrayBuffer(); const downloadTime = (performance.now() - downloadStart) / 1000; results.download = Math.round((downloadSize / downloadTime) / (1024 * 1024) * 8); // 转换为Mbps // 测量上传速度(5MB数据) const uploadSize = 5 * 1024 * 1024; const uploadData = new Blob([new Uint8Array(uploadSize)]); const uploadStart = performance.now(); await fetch('https://speed.cloudflare.com/__up', { method: 'POST', body: uploadData, headers: { 'Content-Type': 'application/octet-stream' } }); const uploadTime = (performance.now() - uploadStart) / 1000; results.upload = Math.round((uploadSize / uploadTime) / (1024 * 1024) * 8); return results; } // 创建并挂载测速按钮 const testBtn = document.createElement('button'); testBtn.textContent = '测试网络速度'; testBtn.addEventListener('click', async () => { testBtn.disabled = true; testBtn.textContent = '测速中...'; try { const results = await runCloudflareSpeedTest(); // 上报到Node.js后端 await fetch('/submit-speed-results', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(results) }); testBtn.textContent = '测试完成'; alert('测速结果已上报'); } catch (err) { testBtn.textContent = '测试失败,请重试'; console.error(err); } finally { testBtn.disabled = false; } }); document.body.appendChild(testBtn);
步骤2:Node.js后端处理上报并写入Google Sheets
使用Google官方的googleapis包实现数据写入,无需第三方工具:
- 先安装依赖:
npm install express googleapis
- 后端代码:
const express = require('express'); const { google } = require('googleapis'); const app = express(); app.use(express.json()); // 配置Google Sheets授权 const auth = new google.auth.GoogleAuth({ keyFile: 'service-account-key.json', // 替换为你的服务账号密钥文件路径 scopes: ['https://www.googleapis.com/auth/spreadsheets'] }); const sheets = google.sheets({ version: 'v4', auth }); // 配置你的电子表格信息 const SPREADSHEET_ID = '你的Google Sheets ID'; const SHEET_NAME = '测速结果'; // 接收前端上报的接口 app.post('/submit-speed-results', async (req, res) => { const { download, upload, ping, timestamp } = req.body; try { await sheets.spreadsheets.values.append({ spreadsheetId: SPREADSHEET_ID, range: `${SHEET_NAME}!A:D`, valueInputOption: 'RAW', resource: { values: [[timestamp, `${download} Mbps`, `${upload} Mbps`, `${ping} ms`]] } }); res.status(200).send('上报成功'); } catch (err) { console.error('上报失败:', err); res.status(500).send('上报失败'); } }); app.listen(3000, () => { console.log('服务运行在http://localhost:3000'); });
关键注意事项
- Cloudflare的
__down/__up端点为公开可用,无需token,测速逻辑与官方控制台一致 - 确保Google Sheets已共享编辑权限给服务账号邮箱(密钥文件中的
client_email字段) - 可根据需求调整下载/上传的文件大小,平衡测速精度与耗时
内容的提问来源于stack exchange,提问作者ike5
相关产品推荐
相关产品推荐

