I have successfully written a code to read unseen emails in my email box using node.js. it works fine when I run it in the normal javascript file. now I want to schedule the script to run every 30 seconds. so wrote a code snippet using node-scheduler as below. running this I just get reading unread emails....###
as output, console.log(msg);
not print anything. if I run this without nod-scheduler it works fine. what might be the problem? I tried await
keyword with email.unreadEmail
function, it didn't work too.
I believe that this is something happening because of asynchronous behavior. if so is there way to convert this code to promises? I am little bit confiuse because there are multiple nexted callback in imap interface.
schedule.scheduleJob('*/30 * * * * *', () => {
logger.info(`scheduler runs at ${new Date()} for check unread emails`);
let email = new mail.default();
email.unreadEmail((msg) => {
console.log(msg);
});
});
here is the code for email reading
unreadEmail(callback){
logger.info(`reading unread emails....###`);
imap.once('ready', () => {
openIncidents((err, box) => {
if (err) throw err;
imap.search([ 'UNSEEN'], (err, results) => {
if (err) throw err;
try{
// var f = imap.fetch(results, { bodies: '',markSeen: true });
var f = imap.fetch(results, { bodies: '' });
f.on('message', (msg, seqno) => {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', (stream, info) => {
simpleParser(stream, (err, mail) => {
callback(mail.subject);
});
// stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt'));
});
msg.once('attributes', function(attrs) {
logger.info(prefix + 'Attributes: %s', inspect(attrs, false, 8));
});
msg.once('end', function() {
logger.info(prefix + 'Finished');
});
});
f.once('error', function(err) {
logger.error('Fetch error: ' + err);
});
f.once('end', function() {
logger.info('Done fetching all messages!');
imap.end();
});
}catch (e) {
logger.error('Error from fetching mails, probably there are no unseen emails in mailbox');
}
});
});
});
logger.info(`end of the email function....###`);
}
Updated
this behavior is same with setInterval
function
setInterval(()=>{
email.unreadEmail((msg)=>{...})}, 30000)
from callback function not working in node-scheduler
No comments:
Post a Comment