-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathwttr_weather.js
36 lines (30 loc) · 1.09 KB
/
wttr_weather.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const https = require('https');
/**
* 获取指定城市的天气信息
* @param {string} city - 城市名
* @param {string} params - wttr.in的查询参数
* @returns {Promise<string>} 天气信息
*/
function getWeather(city = 'Shanghai', params = 'format=3') {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Request timed out'));
}, 15000); // 设置15秒的请求超时
https.get(`https://wttr.in/${encodeURIComponent(city)}?${params}`, (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
clearTimeout(timeout); // 清除超时
resolve(data);
});
}).on("error", (err) => {
clearTimeout(timeout); // 清除超时
reject("Error: " + err.message);
});
});
}
module.exports = getWeather;