Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I've been learning NodeJS recently, and have a small program to get the external IP address on my home network from fugal.net, compare it to the previous IP address, and if there is a change update the stored version, and send an email with the new IP.

I'm running node 0.11.12 on a Raspberry Pi, and storing on mongodb 2.1.1. I would appreciate any recommendations on how to improve it.

var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var nodemailer = require('nodemailer');

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: '[email protected]',
        pass: 'mypassword'
    }
});

var config = {
    hostname: 'fugal.net',
    path: '/ip.cgi',
    agent: false
};

http.request(config, function(res) {

    if(res.statusCode != 200) {
        throw new Error('non-OK status: ' + res.statusCode);
    }
    res.setEncoding('utf-8');
    var ipAddress = '';
    res.on('data', function(chunk) {    ipAddress += chunk; });
    res.on('end', function() {  
        MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

            var collection = db.collection('test');
            collection.findOne({}, function(err, item) {

                var changeNeeded = false;
                if(item.ipAddress != ipAddress) {

                    changeNeeded = true;
                    db.collection('test').update({_id: item._id}, {$set: {ipAddress: ipAddress}}, {w:1}, function(err) {
                        if(err) throw err;
                        db.close();
                    });
                    sendMail(ipAddress);

                }
                if(!changeNeeded)
                    db.close();

            });

        });

    });

}).on('error', function(err) {
    throw err;
}).end();

function sendMail(ipAddress) {

    var mailOptions = {
        from: '[email protected]', // sender address
        to: '[email protected]',   // list of receivers
        subject: 'IP Address Changed',  // Subject line
        text: 'New IP Address: ' + ipAddress       // html body
    };

    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
        }
    });

}

The big stumbling block for me was where to put the call to "db.close()" because of JavaScript's asynchronous nature.

The code to get the IP address was taken from here. The nodemail code is straight from the usage example on http://www.nodemailer.com.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.