如何在Node.js中用setInterval定时获取天气而非仅输出内容?
当然可行!来帮你修正代码实现定时获取天气
你这个思路完全没问题,只是当前代码里有几个小细节没处理对,导致没法实现定时更新天气的需求,咱们一步步调整:
先说说你代码里的问题:
- 你的
intervalFunc函数只是打印了命令行路径,根本没有重新发起天气请求的核心逻辑 setInterval放在了request的回调函数里,这意味着只有第一次请求成功后才会启动定时器,如果请求失败的话定时器根本不会工作- 请求URL里的
main.humidity=%&clouds.all=%是多余的,OpenWeatherMap的weather接口返回的结果默认就包含这些字段,不需要额外指定
修正后的完整代码:
const request = require('request'); const argv = require('yargs').argv; const apiKey = 'my key'; let city = argv.c || 'london'; // 把天气请求逻辑封装成独立函数,方便定时器重复调用 function fetchWeather() { const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`; request(url, function (err, response, body) { if (err) { console.log('请求出错:', err); return; } try { const weather = JSON.parse(body); // 检查API返回的是否是有效数据(避免API返回错误信息) if (weather.cod !== 200) { console.log('API返回错误:', weather.message); return; } const message = `It's ${weather.clouds.all}% cloudy, ${weather.main.humidity}% humid, and ${weather.main.temp}°C in ${weather.name}!`; console.log(message); } catch (parseErr) { console.log('解析天气数据出错:', parseErr); } }); } // 立即执行一次,避免用户等待30秒才看到结果 fetchWeather(); // 每隔30秒执行一次天气请求 const weatherInterval = setInterval(fetchWeather, 30000); // 如果需要手动停止定时器,可以调用:clearInterval(weatherInterval);
额外的实用小建议:
- API调用频率:OpenWeatherMap的免费版有调用次数限制,别把间隔设得太短(比如小于10秒),避免触发限流
- 替换request库:
request已经被官方废弃了,推荐用更现代的库比如axios,或者Node.js 18+支持的原生fetch - 错误处理:代码里加了
try-catch处理JSON解析错误,以及检查API返回的状态码,避免因为API返回错误信息导致程序崩溃
内容的提问来源于stack exchange,提问作者Jay Hills
相关产品推荐
相关产品推荐

