我创建了一个脚本,检查url列表,如果他们的http状态码是200,那么url是向上的,如果他们的http状态码是200以外的任何东西,那么他们是向下的。
我还使用nodemailer设置了一个邮件功能,它发送已关闭的url列表。但现在的问题是,如果所有的url都是有效的,那么它也会发送空邮件。
我想做的是,只发送邮件,如果url是无效的/down url,如果所有的url都是有效的,然后发送任何其他消息,如"没有无效的url "或者干脆不发邮件,退出脚本。
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();
如果我很好地理解了你的问题,那么你应该检查你从returnListOfUrls得到的res,并根据它决定你要发送什么消息。
代码看起来像这样:
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);
}
});
});
};
或者如果你不想发送任何消息,那么:
if(res.length > 0) {
htmlMessage = `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`
} else {
return
}