Mornor
Mornor

Reputation: 3801

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.

Upvotes: 3

Views: 72

Answers (2)

Martin Gottweis
Martin Gottweis

Reputation: 2739

The approach and idea is great. All you need is to change the syntax of mail.js file to return a module. In another words when you do

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

what do you expect to be in the mail variable?

You might need to change logic around, but try this:

var MailHandler = function () {}

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

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

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

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

//fetchMail();

module.exports = new MailHandler()

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 175088

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();
};

Upvotes: 1

Related Questions