Building a Real-Time Weather Alert System in 10 Minutes

·

4 min read

Introduction

Recently, the media has been filled with reports about the unprecedented heavy rainfall that hit Zhengzhou, Henan. Who could have predicted the chaos of flooding in subway stations, leaving passengers trapped? Hearing firsthand accounts from survivors of this disaster invokes feelings of helplessness in the face of sudden calamity.

Here in the High-Tech Zone of Zhengzhou, we too experienced water and power outages. Even now, our broadband signal has yet to be restored, leaving many colleagues connecting via mobile hotspots to continue working.

In this article, we will approach the development of a complete real-time weather alert system using Node.js and a free third-party API from Juhe Data. While we won’t delve into highly complex technologies, the goal is to inspire and provide a practical example.

Step 1: Finding a Free Weather API

There are many free APIs available online to obtain weather data. For this project, I will use Juhe Data's API, which is relatively stable.

Application URL: Juhe API Documentation

Once you apply successfully, a request key will be generated in your account center. You'll need this key to send requests.

Step 2: Using the Weather API and Generating Code

Based on the usage instructions provided by Juhe Data, we can test the API using a tool like EchoAPI.

EchoAPI

You can see that the JSON format of a successful request looks like this:

{
    "reason": "Query successful!",
    "result": {
        "city": "New York",
        "realtime": {
            "temperature": "24",
            "humidity": "100",
            "info": "Light rain",
            "wid": "07",
            "direct": "Northeast wind",
            "power": "Grade 2",
            "aqi": "32"
        },
        "future": [
            {
                "date": "2021-07-23",
                "temperature": "23/28℃",
                "weather": "Light rain turning overcast",
                "wid": {
                    "day": "07",
                    "night": "02"
                },
                "direct": "East wind turning north"
            },
            {
                "date": "2021-07-24",
                "temperature": "24/31℃",
                "weather": "Light rain turning cloudy",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "direct": "Northeast wind turning east"
            },
            {
                "date": "2021-07-25",
                "temperature": "23/31℃",
                "weather": "Cloudy",
                "wid": {
                    "day": "01",
                    "night": "01"
                },
                "direct": "East wind turning southeast"
            },
            {
                "date": "2021-07-26",
                "temperature": "24/31℃",
                "weather": "Light rain",
                "wid": {
                    "day": "07",
                    "night": "07"
                },
                "direct": "Northeast wind"
            },
            {
                "date": "2021-07-27",
                "temperature": "23/31℃",
                "weather": "Light rain turning clear",
                "wid": {
                    "day": "07",
                    "night": "00"
                },
                "direct": "Northeast wind turning south"
            }
        ]
    },
    "error_code": 0
}

At this point, we have obtained the weather data for the next seven days.

Step 3: Sending Emails with Nodemailer in Node.js

We can use Nodemailer in Node.js to send emails easily. You can install it using the following command:

npm install nodemailer

Here’s a function I wrote to send emails, where the email account and authorization code can be obtained from the respective email service provider.

/**
 * Node.js Email Sending Function
 */
function sendEmail(text) {
    let nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
        service: "126",  // Email service
        secure: true,    // Secure sending mode
        auth: {
            user: "be***er@126.com", // Sender's email
            pass: "MLQ***PYU"  // Authorization code, obtainable from the email service provider
        }
    });

    let mailOptions = {
        from: "be***er@126.com", // Sender's email, must match above
        to: "3257132998@qq.com", // Recipient's email for receiving weather alerts
        subject: "Real-Time Weather Monitoring System", // Email subject
        text: text // Email body
    };

    transporter.sendMail(mailOptions, (err, data) => {
        if (err) {
            console.log(err);
            res.json({ status: 400, msg: "Send failed..." });
        } else {
            console.log(data);
            res.json({ status: 200, msg: "Email sent successfully..." });
        }
    });
}

// Test email sending
sendEmail('It is raining!');

Create a file named weather.js, and input the above code. You can test the email sending with the command:

node weather.js

You should see a successful email sent.

Step 4: Periodically Fetching Weather Data in Node.js

By clicking the "Generate Node.js (Request)" code in EchoAPI, you can generate the program code to request the Juhe Weather API. We can use setInterval to implement the desired functionality.

Generate Node.js (Request)

Here’s the complete code:

/**
 * Node.js Email Sending Function
 */
function sendEmail(text) {
    let nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
        service: "126",  // Email service
        secure: true,    // Secure sending mode
        auth: {
            user: "be***er@126.com", // Sender's email
            pass: "MLQ***PYU"  // Authorization code
        }
    });

    let mailOptions = {
        from: "be***er@126.com", // Sender's email
        to: "3257132998@qq.com", // Recipient's email
        subject: "Real-Time Weather Monitoring System", // Email subject
        text: text // Email body
    };

    transporter.sendMail(mailOptions, (err, data) => {
        if (err) {
            console.log(err);
            res.json({ status: 400, msg: "Send failed..." });
        } else {
            console.log(data);
            res.json({ status: 200, msg: "Email sent successfully..." });
        }
    });
}

setInterval(function() {
    var request = require('request');

    var headers = {
        'User-Agent': 'EchoAPI client Runtime/+https://www.echoapi.com/'
    };

    var options = {
        url: 'http://apis.juhe.cn/simpleWeather/query?city=%E9%83%91%E5%B7%9E&key=8763efe2a90b025c03e03fef95621cbc',
        headers: headers
    };

    function callback(error, response, body) {
        let json = JSON.parse(body);
        console.log(json.result);
        if (!error && response.statusCode == 200) {
            sendEmail('Zhengzhou Weather: ' + json.result.future[0].weather);
        }
    }

    request(options, callback);

}, 300000); // Fetch weather every 5 minutes

And there you have it! The entire system has been set up. We just need to run the following command on a small server:

node weather.js

This will send weather updates to the specified email every 5 minutes, although you can adjust this interval as needed.

Notes:

Please note that due to potential issues with UTF-8 encoding in requests, it's best to encode city names (right-click to encode) to avoid errors.

Try EchoAPI Interceptor today! https://www.echoapi.com/plugin/chrome?utm_source=6715d073