Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Javascript object - Scope issue with Node.js

I'd like to fetch mail from a mailbox regularly using a Node daemon. The call to the connection method is made in app.js.

The javascript file I use to connect to my mailbox (mail.js):

var imap = new Imap({
    user: '[email protected]',
    password: config.get.gmail_password,
    host: 'xxxxx',
    port: 993,
    tls: true
});

var fetchMail = function()
{
    console.log('Connection');
    imap.connect();
};

//fetchMail();

imap.once('ready', function() {
   console.log('Ready'); 

   imap.search([ 'UNSEEN', ['FROM', 'xxxx'] ], function(err, results)
   {
       // Do Stuff
   }

exports.fetchMail = fetchMail;

If I use fetchMail() directly from mail.js, everything is fine.

However, when I try to call it from app.js:

var mail = require('./js/mail');
mail.fetchMail() 

Then, the method stay in the fetchMail() function from mail.js and the imap.once('ready', function())is never triggered.

I guess it is a scope issue with the imap var in mail.js.

How can I fix this?

EDIT

I solved this in a way I don't like. I wrote everything's related to the imap var inside the fecthMail()function.

Please, do not hesitate to write a more efficient answer to this.

like image 437
Mornor Avatar asked Dec 13 '25 21:12

Mornor


1 Answers

You would need to bind the event every time you connect. So like so:

var fetchMail = function()
{
    console.log('Connection');

    imap.once('ready', function() {
      console.log('Ready');         
      imap.search([ 'UNSEEN', ['FROM', 'xxxx'] ], function(err, results)
      {
        // Do Stuff
      }
    }
    imap.connect();
};
like image 192
Madara's Ghost Avatar answered Dec 15 '25 09:12

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!