Stap 4: De Node.js toepassing (app.js)
Het hoofdtoepassingsbestand zullen:
Allereerst de vereist (nodemailer, nodemailer-smtp-transport, fs en de reeds gemaakte config.js )
// Variable declaration and requiresvar exec = require('child_process').exec;var nodeMailer = require('nodemailer');var smtpTransport = require('nodemailer-smtp-transport');var serverOptions = require('./config.js').getServerOptions();var mailOptions = require('./config.js').getMailOptions();var intervalMinutes = require('./config.js').getServerInterval();var fs = require('fs');var sendServer = nodeMailer.createTransport(smtpTransport(serverOptions));var logStream = fs.createWriteStream("log.txt", {'flags': 'a'});var lastIP = "";// The function responsible for sending the mailvar sendMail = function(ipAddress){ var msg= "---------------------------\n"; msg += "SendMail : " + ipAddress ; mailOptions.text = ipAddress mailOptions.html = "" + ipAddress + ""; sendServer.sendMail(mailOptions, function(error, info){ if (error){ msg += "Err : " + error; logStream.write(" SendMail.Err : " + error); console.log(error); }else{ console.log('Message sent: ' + info.response); msg += info.response ; } msg += "\n---------------------------\n"; logStream.write(msg); })};// Getting the external IP addressvar getExternalIp = function(errorCallback,successCallback){ var child = exec("dig +short myip.opendns.com function (error, stdout, stderr) { if (error !== null) { errorCallback(error); }else{ var dt = new Date(); var dtSt = dt.getFullYear() + '-' + ("0" + (dt.getMonth() + 1)).slice(-2) + '-' + ("0" + (dt.getDate() + 1)).slice(-2) + ' ' + ("0" + dt.getHours()).slice(-2) + ':' + ("0" + dt.getMinutes()).slice(-2) + ':' + ("0" + dt.getSeconds()).slice(-2) logStream.write(dt + " : " + stdout) ; if (stdout != lastIP){ var lastStream = fs.createWriteStream("last.txt"); lastStream.write(stdout); lastIP = stdout successCallback(stdout); } }});}// Error callback to be called on next twovar errorFunction = function(err){ logStream.write("ERR : " + err);}// Main Timer to poll IP and send email if it changedfunction startTimer(){ setInterval(function(){ getExternalIp(errorFunction, sendMail); }, 60000 * intervalMinutes);}// Each launch of the application, reads the last obtained IP from a manual created file (last.txt)fs.readFile('./last.txt', 'utf8' , function(err, data){ if (err) throw err; else{ var dt = new Date(); var dtSt = dt.getFullYear() + '-' + ("0" + (dt.getMonth() + 1)).slice(-2) + '-' + ("0" + (dt.getDate() )).slice(-2) + ' ' + ("0" + dt.getHours()).slice(-2) + ':' + ("0" + dt.getMinutes()).slice(-2) + ':' + ("0" + dt.getSeconds()).slice(-2) lastIP = data; logStream.write("\n"); logStream.write("\n"); logStream.write("*****************************************\n"); logStream.write(dtSt) ; logStream.write("\n"); console.log("startServer:lastIP : " + lastIP); logStream.write("START_SERVER : lastIP : " + lastIP + "\n"); getExternalIp(errorFunction, sendMail); setTimeout(startTimer, 10000); }})