I've create a script which checks a list of urls, and if their http status code is 200 then the urls are up and if their http status code is anything other than 200 then they are down.
I've also setup a mail function using nodemailer, which sends list of urls which are down. But right now the problem is if all the urls are valid then also it sends the empty mail.
What I want to do is , only send mail if the urls are invalid/down urls and if the all the urls are valid then send any other message like "No invalid urls" or just dont send any email and exit the script.
const request = require("request");
const nodemailer = require("nodemailer");
// list of urls that need to be checked
const urlList = [
// valid url (returns http 200)
"https://google.com/",
// invalid url (returns http 404 not found)
"https://googglslfdkfl.com/",
];
// e-mail setup
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: "email",
pass: "password",
},
secure: false,
});
//get the http status code
function getStatus(url) {
return new Promise((resolve, reject) => {
request(url, function (error, response, body) {
resolve({
site: url,
status:
!error && response.statusCode == 200
? "OK"
: "Down: " error.message,
});
});
});
}
let promiseList = urlList.map((url) => getStatus(url));
// return a list of only the sites in an array with status of Down
const returnListOfUrls = Promise.all(promiseList).then((resultList) => {
const listWithDownStatus = resultList
.map((result) => result.status.startsWith("Down") && result.site)
.filter(Boolean);
return listWithDownStatus;
});
const runNodeMailer = () => {
returnListOfUrls.then((res) => {
const message = {
from: "from-email",
to: "to-email",
subject: "test",
html: `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`,
};
console.log(res, "---", message);
transporter.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
});
};
runNodeMailer();
CodePudding user response:
If I understand your question well, than you should check res that you get from returnListOfUrls and based on that decide what message you are sending.
Code would look like this:
const runNodeMailer = () => {
returnListOfUrls.then((res) => {
let htmlMessage = ''
if(res.length > 0) {
htmlMessage = `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`
} else {
htmlMessage = `<h1>You have no issues with urls</h1>` }
const message = {
from: "from-email",
to: "to-email",
subject: "test",
html: htmlMessage,
};
console.log(res, "---", message);
transporter.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
});
};
Or if you don't want to send any message, than do:
if(res.length > 0) {
htmlMessage = `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`
} else {
return
}