简体   繁体   中英

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: 'xxxx@hotmail.com',
    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.

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

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: 'xxxx@hotmail.com',
    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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM