Search code examples
javascriptnode.jsdom-eventsnodemailer

How to get the date every time a day passes in nodejs?


What I intend to do is a program that sends congratulatory emails for their birthday to several users, then the program will take today and execute a query to the database (it is an Excel file), in which it will take the date of the users and compare their date of birth with the current date, if the month and day coincide, mail will be sent. I think it can be done with a setInterval(), but I don't know if it affects the performance of the program. Since it will be uploaded on a windows server 2012 server of my company.

My code:

const express = require("express");
const app = express();
const excel = require('./public/scripts/readExcel.js');
const email = require('./services/email/sendEmail.js');
     
app.post('/send-email',(req, res)=>{
  setInterval(() => {
    email.sendEmail()
    .then((result) => {
        res.status(200).jsonp(req.body);;
        console.log(result)
    }).catch((err) => {
        res.status(500).jsonp(req.body);;
        console.log(err);
    });
  }, 3600000);//1 hour
    
});
app.listen(4000, ()=>{
    console.log("Serven on -> http://localhost:4000");
})

Basically what it does is call the sendEmail function every hour which reads the Excel file or the database and extracts the date fields, compares with the current day, and sends the mail with Nodemailer to those who have birthdays. Also, the setInterval would go in the route of "/send-email" or how would the request be made?


Solution

  • For that, you can also run a cron job at every hour using npm package cron-job using

    var cron = require('node-cron');
    
    cron.schedule('* * 1 * *', () => {
      console.log('running a task every hour');
    });